介绍几个常用的JS数组函数

filter、forEach、map、reduce、splice、sort

1. filter

filter() 方法创建一个新的数组并返回, 新数组中的元素一定是原数组中的元素, 不改变原来的数组. 过滤原数组产生新数组.

array.filter(function(currentValue,index,arr), thisValue)

thisValue(对象)用作回调函数中的 “this” 的值

若使用箭头函数: array.filter((currentValue,index,arr) => {}), 在箭头函数里使用this, 当前无this就会去父作用域寻找.

2. forEach

数组每个元素都执行一次回调函数.

array.forEach(function(currentValue, index, arr), thisValue)

3. map

通过指定函数处理数组的每个元素, 并返回处理后的数组.

返回一个新数组, 数组中的元素为原始数组元素调用函数处理后的值.

array.map(function(currentValue,index,arr), thisValue)

4. reduce

将数组元素计算为一个值(从左到右).

接收一个函数作为累加器, 数组中的每个值(从左到右)开始缩减, 最终计算为一个值.

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

initialValue: 计算的初始值.

5. splice

从数组中添加或删除元素.

array.splice(index,howmany,item1,…,itemX)

6. sort

对数组元素重新排序.

array.sort(sortfunction)


评论