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 [{...}]
.map()
map函数是es6的遍历器,在遍历完成之前无法停止。返回值为符合条件的新数组,不改变原数组。
map((item, index, array) => {代码 return{}}),函数有三个参数,item为当前循环的元素,index为当前循环的角标,arrar为当前数组。里面为代码循环体, 返回值指定的值。如果只取一个字段的值可以简写为list.map(item => item.id)
1 // 便利list数组 2 list.map((item, index, array) => { return {id: item.id, index, item: array[index]}}) 3 //结果为 4 // {id: 1, index: 0, item: {…}} 5 // {id: 2, index: 1, item: {…}}
6 // 如果只取一个字段的值可以简写为
7 list.map(item => item.id)
8 // [1, 2, 3, 4, 5, 6]

浙公网安备 33010602011771号