js--数组方法

.filter()

filter函数是筛选目标数组中符合方法内条件的元素,并返回一个包含所有符合元素的新数组。

filter((item, index, array) => {代码 return Boolen}),函数有三个参数,item为当前循环的元素,index为当前循环的角标,arrar为当前数组。里面为代码循环体,Boolen为true时返回当前元素,false时不返回元素。

1 // 过滤大于等于10的数
2 let arr = [1, 3, 7, 10, 17, 0, 2]
3 arr.filter(o => o >= 10)
4 //结果为 [10, 17]

.forEach()

forEach函数是es6的遍历器,在遍历完成之前无法停止。无返回值。这个遍历器只能便利数组。

forEach((item, index, array) => {代码}),函数有三个参数,item为当前循环的元素,index为当前循环的角标,arrar为当前数组。里面为代码循环体。

 1 // 遍历list数组
 2 let list = [
 3         {id: 1, name: 'kk', parentId: 0},
 4         {id: 2, name: 'kk', parentId: 1},
 5     ] 
 6 
 7 list.forEach((item, index, array) => {
 8     console.log(item, index, array)
 9 })
10 // 结果为
11 // {id: 1, name: 'kk', parentId: 0}  0  [{...}]
12 // {id: 2, name: 'kk', parentId: 1}  1  [{...}]

猜你喜欢

转载自www.cnblogs.com/wxliang/p/13390106.html
今日推荐