Hello,World.

秋风与你,偏安一隅.

遍历数组的各种方法

for(var i=0;i<arr.length;i++){    //for循环为最简单循环数据方法,根据下标取数组值        
console.log(arr[i]+"\n")
}
 
arr.forEach(function(val,index){    //forEach为ES5支持的遍历方法,不能使用break和return
    console.log(val+"\n")
})
 
for(var index in arr){    //元素下标不是数字类型,可能会随机遍历元素
  console.log(arr[index]+"\n")  
}
 
for(var val of arr){    //ES6语法,与基础for循环类似,取下标需要将数组转一次map
    console.log(val+"\n")
}
 
arr.some((item, index, arr) => {    // item为数组中的元素,index为下标,arr为目标数组;some意思为有一些条件满足即返回true
    console.log(item); // 1, 2, 3
    console.log(index); // 0, 1, 2
    console.log(arr); // [1, 2, 3] 
    return item === 2 //true 
})
 
arr.every((item, index, arr) => { // item为数组中的元素,index为下标,arr为目标数组;every意思为必须所有元素满足才返回true;
    return item > 0; // true
    return index == 0; // false
})
 
var arr = [1, 2, 3]
for(var item in arr) {    // item遍历数组时为数组的下标,遍历对象时为对象的key值
    console.log(item); // 0, 1, 2
};
 
arr.filter(item => { // item为数组当前的元素;filter意思为将满足条件的项组合成一个数组返回
    return item > 1; // [2, 3]
})
 
arr.map(item => { // item为数组的元素;map意思为将元素的所有项执行一个操作后重新组合成数组返回
    console.log(item); // 1, 2, 3
    return item * 2; // 返回一个处理过的新数组[2, 4, 6]
})
posted @ 2021-03-09 13:52  秋风荡  阅读(212)  评论(0编辑  收藏  举报