Open nfssuzukaze opened 3 years ago
参数:
item
index
array
callback_this
this
arr.forEach(callback(item, index?, array?), callback_this?)
作用: 对数组进行遍历, 并利用 回调函数 进行一定的处理 返回值: undefined
undefined
参数: (与 forEach 一样)
arr.filter(callback(item, index?, array?), callback_this?)
作用: 对数组进行遍历, 根据 回调函数 的返回值来过滤数组元素(返回 true 则留下, 返回 false 则筛除) 返回值: 经过 filter 的回调函数过滤后的数组
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]
arr.map(callback(item, index?, array?), callback_this?)
作用: 对数组进行遍历, 每个回调函数的返回值都是新数组对应项的值 返回值: 经过 map 的回调函数处理后的数组
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]
arr.reduce(callback(accumulator, currentValue, index, array), initialValue)
作用: 遍历数组的所有元素, 并通过 回调函数 将其处理成一个值
initialValue
accumulator
返回值: 经过 reduce 的回调函数处理后的值
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
JS 的 Array 类型所对应的一些常见 API
1. 本身不改变原数组
1.1 forEach
参数:
item
: 数组当前项的值(基本类型是值, 引用类型是地址)index
: 数组当前项的索引array
: 数组本身callback_this
: 回调函数执行时所对应的this
指向作用: 对数组进行遍历, 并利用 回调函数 进行一定的处理 返回值:
undefined
1.2 filter
参数: (与 forEach 一样)
作用: 对数组进行遍历, 根据 回调函数 的返回值来过滤数组元素(返回
true
则留下, 返回false
则筛除) 返回值: 经过filter
的回调函数过滤后的数组1.3 map
参数: (与 forEach 一样)
作用: 对数组进行遍历, 每个回调函数的返回值都是新数组对应项的值 返回值: 经过
map
的回调函数处理后的数组1.4 reduce
作用: 遍历数组的所有元素, 并通过 回调函数 将其处理成一个值
initialValue
指定accumulator
的初值, 那么默认其初值为数组第一个元素的值, 然后从数组的第二个元素开始遍历返回值: 经过
reduce
的回调函数处理后的值