迭代方法
every() 检测数组的每一个元素是否满足条件 true false
some() 检测数组的元素是否有一个满足条件 一个满足 返回true
map() 映射 对每一个数组元素操作
filter() 过滤 过滤出符合条件的元素组成新数组
forEach() for循环的升级版
// every方法 对每一个数组元素进行检测 全部检测通过true false
// 重构every方法
// fun接受的是function(item){
// return item>0
// }
// Array.prototype.myEvery=function(fun){
// for(var i=0;i<this.length;i++){
// if(!fun(this[i])){
// return false
// }
// }
// return true
// };
// var arr=[1,2,3,4,5];
// // item --this[i]=>arr[i]
// var result=arr.myEvery(function(item){
// return item>1
// });
// console.log(result,'返回值');
// function test(fun){
// fun(this[i])
// }
// test(function(item){
// return item+1
// })
// 重构mySome
// Array.prototype.mySome=function(fun){
// for(var i=0;i<this.length;i++){
// if(fun(this[i])){
// return true
// }
// }
// return false
// }
// var arr=[1,2,3,4,5];
// var result=arr.mySome(function(item){
// return item>4
// });
// console.log(result);
// 重构filter方法
// Array.prototype.myFilter=function(fun){
// let newArr=[];
// for(i=0;i<this.length;i++){
// if(fun(this[i])){
// // 把符合条件的数组元素添加到新数组中
// newArr.push(this[i])
// }
// }
// return newArr
// }
// var arr=[1,2,3,4,5];
// var result=arr.myFilter(function(item){
// return item>1
// })
// console.log(result);
// 重构map方法
// Array.prototype.myMap=function(fun){
// let newArr=[];
// for(i=0;i<this.length;i++){
// newArr.push(fun(this[i]))
// }
// return newArr
// }
// var arr=[1,2,3,4,5];
// var result=arr.myMap(function(item){
// return item + 2
// });
// console.log(result);
// 重构forEach方法
Array.prototype.myForEach=function(fun){
for(i=0;i<this.length;i++){
fun(this[i],i,this)
}
}
var arr=[1,2,3,4,5,'hello'];
// for(i=0;i<arr.length;i++){
// console.log(i,arr[i],arr)
// }
var result=arr.myForEach(function(item,index,arr){
console.log(item,index,arr);
})
console.log(result);