Array.prototype.every()
every() 方法用于检测数组所有元素是否都符合指定条件(通过函数提供)。
every() 方法使用指定函数检测数组中的所有元素:
注意: every() 不会对空数组进行检测。
注意: every() 不会改变原始数组。
//every() 方法用于检测数组所有元素是否都符合指定条件(通过函数提供 Array.prototype.myEvery =function(fun,obj) { //fun obj console.log(obj,'obj'); for(i = 0;i < this.length;i++){ // fun.bind(obj)(this[i]) 有第二个参数就改变this指向 if(!(obj?fun.bind(obj)(this[i]) : fun(this[i]))) { //fun.bind(obj)(this[i])为false //bind() 会把obj和this[i]转换成函数并改变他们的指向 均可调用匿名函数myEvery() return false; } } return true; } var arr = [1,2,3,4]; var result = arr.myEvery(function(item){ //回调函数 console.log(this,'this'); //指向全局对象 //{ name: 'zhang' } return item > 1;//return false //短路原则 1 > 1 不大于 短路 停止检测数组 },{name:'zhang'}) //改变this指向 指向第二个参数 console.log(result,'result'); //false
Array.prototype.some()
some() 方法用于检测数组中的元素是否满足指定条件(函数提供)。
some() 方法会依次执行数组的每个元素:
注意: some() 不会对空数组进行检测。
注意: some() 不会改变原始数组。
// some() 方法用于检测数组中的元素是否满足指定条件(函数提供) //如果有一个元素满足条件,则表达式返回*true* , 剩余的元素不会再执行检测 Array.prototype.mySome =function(fun,obj) { //fun obj for(i = 0;i < this.length;i++){ // fun.bind(obj)(this[i]) 有第二个参数就改变this指向 if((obj?fun.bind(obj)(this[i]) : fun(this[i]))) { return true; } } return false; } var arr = [1,2,3,4]; var result = arr.mySome(function(item){ //回调函数 console.log(this); //指向全局对象 return item > 1; //短路原则 1 > 1 不大于 短路 // 2 > 1 满足条件 打印输出为真 停止检测数组 },{name:'zhang'}) //改变this指向 指向第二个参数 console.log(result); //true //数组第二个元素满足条件 返回true
Array.prototype.filter()
filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。
注意: filter() 不会对空数组进行检测。
注意: filter() 不会改变原始数组。
// filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素 //主函数 Array.prototype.myFilter = function (fun,obj) { // 创建一个新的数组 var result = []; for(i = 0;i2; // 数组索引值累加 },{name:'zhang'}) //改变this指向 指向第二个参数 console.log(result); //[ 2, 3, 4, 5 ] //返回一个新数组,数组中的元素为原始数组元素调用函数处
Array.prototype.map()
map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。
map() 方法按照原始数组元素顺序依次处理元素。
注意: map() 不会对空数组进行检测。
注意: map() 不会改变原始数组。
// map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值 Array.prototype.myMap = function (fun,obj) { var result = []; for(i = 0;iArray.prototype.forEach()
forEach() 方法用于调用数组的每个元素,并将元素传递给回调函数。
注意: forEach() 对于空数组是不会执行回调函数的。
Array.prototype.myforEach = function (fun) { for(var i = 0;i < this.length;i++){ //调用参数 fun(this[i],i,this) } } var arr = [1,4,2,9]; console.log(arr); // [ 1, 4, 2, 9 ] var result = arr.myforEach(function(item, index, arr){ console.log(item, index, arr); //数组元素 数组元素索引下标 数组 // 1 0 [ 1, 4, 2, 9 ] // 4 1 [ 1, 4, 2, 9 ] // 2 2 [ 1, 4, 2, 9 ] // 9 3 [ 1, 4, 2, 9 ] });