遍历数组的n种方法

<script>
var arr = [1,2,3,4,5]

// arr.forEach(function(item){
// // 当 item =2 的时刻 打印123 同时让 轮回住手
// // forEach 停不下来 它会把数组中每个成员 都去实行回调函数
// if(item==2){
// return true;
// }
// console.log(item)
// })

// this.list.some((item, i) => {
// if (item.id == id) {
// this.list.splice(i, 1)
// // 在 数组的 some 要领中,假如 return true,就会马上住手这个数组的后续轮回
// return true;
// }
// ES6 新增的数组要领
// var res = arr.some(function(item){
// if(item == 2){
// return true
// }
// console.log(item)
// })

// console.log(res)

// 会返回住手时轮回到的数组成员的索引值 住手findIndex轮回的体式格局为 return true
// var res = arr.findIndex(function(item){
// // if(item == 2){ //索引为1的成员这里住手的轮回
// // return true
// // }
// console.log(item)
// })

// console.log(res)

// forEach 没有返回值
// some 要么是true 要么是false
// findIndex 返回的是一个索引值 假如轮回没有被住手 返回的值是-1 假如被住手返回的是当前轮回到的成员的索引值
// map 返回的是一个新的数组需要回调函数return一个值
// map 不会影响原数组

// var res = arr.map(function(item){
// item = item+2 //map中回调函数不return map返回值的新数组成员就是undefined
// })
// console.log(res,arr)
// filter这个数组要领的作用是过滤数组的成员
// 不会转变数组成员的值 假如return true 就把当前轮回到的成员返回到新的数组中
var res = arr.filter(function(item){
if(item!=3){ // 1 2 4 5
return true //return true
}
// 假如不return 那末 filter的返回值的新数组 内里就为空
})
console.log(res,arr)

</script>

    原文作者:yang
    原文地址: https://segmentfault.com/a/1190000018559838
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞