遍历数组的n种方法

9次阅读

共计 1038 个字符,预计需要花费 3 分钟才能阅读完成。

<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 5return true //return true}// 如果不 return 那么 filter 的返回值的新数组 里面就为空 })console.log(res,arr)
</script>

正文完
 0