JS数组常用方法
前言
常用数组方法。
一、数组循环
常用的数组循环有以下六种
1. forEach
用法如下(示例):
/**
* 方法说明
* @param {Object} currentValue 当前元素 必需
* @param {Number} index 当前元素的索引值 可选
* @param {Array} arr 当前元素所属数组对象 可选
* @return 无
*/
let arr = [a,b,c] // 此处定义的 arr 应用于全文,后不再重复定义
arr.forEach((currentValue, index, arr)=>{
// do something
})
console.log(arr)
forEach会遍历数组, 没有返回值, 不允许在循环体内写return, 不会改变原来数组的内容.forEach()也可以循环对象。
2. Map
用法如下(示例):
/**
* 方法说明
* @param 参照forEach
* @return {Array} newArr 返回一个新的数组对象
*/
arr.map((currentValue, index, arr)=>{
// do something
})
console.log(arr)
map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。 map() 方法按照原始数组元素顺序依次处理元素。 注意: map() 不会对空数组进行检测。 注意: map() 不会改变原始数组
3. Filter
用法如下(示例):
/**
* 方法说明
* @param 参照forEach
* @return {Array} newArr 返回包含了符合条件的所有元素的新数组。如果没有符合条件的元素则返回空数组
*/
arr.filter((currentValue, index, arr)=>{
// do something
})
console.log(arr)
filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。 注意: filter() 不会对空数组进行检测。 注意: filter() 不会改变原始数组
4. Reduce
用法如下(示例):
/**
* 方法说明
* @param 参照forEach
* @param {Number} total 初始值, 或者计算结束后的返回值 必需
* @param {Number} initialValue 传递给函数的初始值 可选
* @return {Array} newArr 返回计算结果
*/
const arr = [1,2,3]
arr.reduce((total,currentValue, index, arr)=>{
// do something
return total + currentValue
},initialValue)
console.log(arr) //
reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。 reduce() 可以作为一个高阶函数,用于函数的 compose。 注意: reduce() 对于空数组是不会执行回调函数的 注意:eslint严格模式下initialValue不传程序会报错