nfssuzukaze / Blog

0 stars 0 forks source link

Array API #21

Open nfssuzukaze opened 3 years ago

nfssuzukaze commented 3 years ago

JS 的 Array 类型所对应的一些常见 API

1. 本身不改变原数组

1.1 forEach

参数:

arr.forEach(callback(item, index?, array?), callback_this?)

作用: 对数组进行遍历, 并利用 回调函数 进行一定的处理 返回值: undefined

1.2 filter

参数: (与 forEach 一样)

arr.filter(callback(item, index?, array?), callback_this?)

作用: 对数组进行遍历, 根据 回调函数 的返回值来过滤数组元素(返回 true 则留下, 返回 false 则筛除) 返回值: 经过 filter 的回调函数过滤后的数组

let arr = [1, 2, 3, 4, 5]
let ans = arr.filter(item => item >= 3)
console.log(ans) //=> [3, 4, 5]
console.log(arr) //=> [1, 2, 3, 4, 5]

1.3 map

参数: (与 forEach 一样)

arr.map(callback(item, index?, array?), callback_this?)

作用: 对数组进行遍历, 每个回调函数的返回值都是新数组对应项的值 返回值: 经过 map 的回调函数处理后的数组

let arr = [1, 2, 3, 4, 5]
let ans = arr.map(item => item * item)
console.log(ans) //=> [1, 4, 9, 16, 25]
console.log(arr) //=> [1, 2, 3, 4, 5]

1.4 reduce

arr.reduce(callback(accumulator, currentValue, index, array), initialValue)

作用: 遍历数组的所有元素, 并通过 回调函数 将其处理成一个值

返回值: 经过 reduce 的回调函数处理后的值

let arr = [1, 2, 3, 4, 5]
let ans = arr.reduce((accumulator, curentValue, index) => {
    console.log(accumulator, curentValue, index)
    return accumulator + curentValue
}) 
//=> 1 2 1, 3 3 2, 6 4 3, 10 5 4
console.log(arr) //=> [1, 2, 3, 4, 5]
console.log(ans) //=> 15
let res= arr.reduce((accumulator, curentValue, index, arr) => {
    console.log(accumulator, curentValue, index)
    return accumulator + curentValue
}, 1) 
//=> 1 1 0, 2 2 1, 4 3 2, 7 4 3, 11 5 4
console.log(res) //=> 16