map, filter, reduce。各自的作用
array.map(function(currentValue,index,arr), thisValue)
[1, 2, 3].map(v => v + 1) // -> [2, 3, 4]
生产新的数组(1,2,3元素的索引分别为0,1,2)
['1','2','3'].map(parseInt)
......map(parseInt(1,0))
// filter同map类似,回调参数也类似
let array = [1, 2, 4, 6]
let newArray = array.filter(item => item !== 6)
console.log(newArray) // [1, 2, 4]
// reduce (把数组的各个元素相加)
const arr = [1, 2, 3]
let total = 0
for (let i = 0; i < arr.length; i++) {
total += arr[i]
}
console.log(total) //6
const arr = [1, 2, 3]
// callbackFn(累计值、当前元素、当前索引、原数组)4个参数
// 第1轮的累计值,会当做第二轮的当前值
const sum = arr.reduce((acc, current) => acc + current, 0)// 回调函数、初始值
console.log(sum)
网友评论