数组方法实现
forEach方法
forEach()方法用于遍历数组
- 注意:forEach() 不会对空数组进行检测。
- 注意:forEach() 不会改变原始数组。
| 参数 | 描述 | 是否必填 | | —- | —- | —- | | currentValue | 当前元素 | 必填 | | index | 当前元素的索引值 | 可选 | | arr | 可选当前元素所属的数组对象 | 可选 | | thisValue | 如果这个参数为空, “undefined” 会传递给 “this” 值 | 可选 |array.forEach(function(currentValue, index, arr), thisValue)
Array.prototype.myForEach = function(func){var len = this.lengthvar _this = arguments[1] || windowfor(var i = 0; i < len; i++){func.apply(_this, [this[i], i, this])}}
filter方法
filter() 方法返回一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。
- 注意:filter() 不会对空数组进行检测。
注意:filter() 不会改变原始数组。
Array.prototype.myFilter = function(func){var arr = []var len = this.lengthvar _this = arguments[1] || windowfor(var i = 0; i < len; i++){func.apply(_this, [this[i], i, this]) && arr.push(this[i])}return arr}
map方法
map() 方法按照原始数组元素顺序依次处理元素,会返回一个新数组。
注意:map() 不会对空数组进行检测。
注意:map() 不会改变原始数组。
Array.prototype.myMap = function(func){var arr = [];var len = this.length;var _this = arguments[1] || window;for(var i = 0; i < len; i++){arr.push(func.apply(_this,[this[i],i,this]));}return arr;}
every方法
检测数值元素的每个元素是否都符合条件。
注意:every() 不会对空数组进行检测。
注意:every() 不会改变原始数组。
Array.prototype.myEvery= function(func){var flag = true;var len = this.length;var _this = arguments[1] || window;for(var i = 0; i < len; i++){if(func.apply(_this,[this[i],i,this]) == false){flag = false;break;};}return flag;}
some方法
检测数组元素中是否有元素符合指定条件。
注意:some() 不会对空数组进行检测。
注意:some() 不会改变原始数组。
Array.prototype.mySome= function(func){var flag = true;var num = 0;var len = this.length;var _this = arguments[1] || window;for(var i = 0; i < len; i++){if(func.apply(_this, [this[i], i, this])){break;}else{num ++;if(num == len-1){flag = false;break;}}}return flag;}
reduce方法
将数组元素计算为一个值(从左到右)。
注意:reduce() 对于空数组是不会执行回调函数的。
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
| 参数 | 描述 | 是否必填 | | —- | —- | —- | | total | 初始值,或者计算结束后的返回值 | 必填 | | currentValue | 当前元素 | 必填 | | currentIndex | 当前元素的索引 | 可选 | | arr | 当前元素所属的数组对象 | 可选 | | initialValue | 传递给函数的初始值 | 可选 |
Array.prototype.myReduce = function(func, initValue){var len = this.lengthvar _this = arguments[0] || windowvar nextValue = initValuefor(var i = 0; i < len; i++){nextValue = func.apply(_this,[initValue, this[i], i, this])}return nextValue}
apply、call、bind方法实现
apply
改变this指向,参数为数组
