一、数组遍历方法
| 方法 | 使用示例 | 是否改变原数组 | 返回值 | 作用 |
|---|---|---|---|---|
forEach() | arr.forEach(element => console.log(element)) | 否 | 无 | 遍历数组,对每个元素执行函数 |
for...of 循环 | for (const value of arr) console.log(value) | 否 | 无 | 遍历数组的值 |
二、数组转换与映射方法
| 方法 | 使用示例 | 是否改变原数组 | 返回值 | 作用 |
|---|---|---|---|---|
map() | let newArr = arr.map(element => element *2) | 否 | 新数组,包含每次函数调用结果 | 创建新数组,每个元素执行函数 |
filter() | let newArr = arr.filter(element => element > 3) | 否 | 新数组,包含符合条件元素 | 创建新数组,包含符合条件的元素 |
concat() | let newArr = arr.concat(otherArray) | 否 | 新数组 | 合并数组 |
slice() | let newArr = arr.slice(start, end) | 否 | 新数组 | 提取数组的一部分 |
flat() | let newArr = arr.flat(depth) | 否 | 新数组 | 将数组扁平化 |
flatMap() | let newArr = arr.flatMap(element => newArray) | 否 | 新数组 | 映射并扁平化数组 |
三、数组添加与删除方法
| 方法 | 使用示例 | 是否改变原数组 | 返回值 | 作用 |
|---|---|---|---|---|
push() | let newLength = arr.push(newElement) | 是 | 新数组长度 | 添加元素到数组末尾 |
pop() | let element = arr.pop() | 是 | 被删除的元素 | 删除数组末尾元素 |
shift() | let element = arr.shift() | 是 | 被删除的元素 | 删除数组开头元素 |
unshift() | let newLength = arr.unshift(newElement) | 是 | 新数组长度 | 添加元素到数组开头 |
splice() | let removed = arr.splice(startIndex, deleteCount) | 是 | 被删除元素数组 | 删除、替换或添加元素 |
四、数组查找与检测方法
| 方法 | 使用示例 | 是否改变原数组 | 返回值 | 作用 |
|---|---|---|---|---|
every() | let result = arr.every(element => element < 6) | 否 | 布尔值,true 或 false | 测试所有元素是否符合条件 |
some() | let result = arr.some(element => element > 4) | 否 | 布尔值,true 或 false | 测试是否有元素符合条件 |
indexOf() | let index = arr.indexOf(targetElement) | 否 | 索引值或 -1 | 查找元素第一次出现的索引 |
lastIndexOf() | let index = arr.lastIndexOf(targetElement) | 否 | 索引值或 -1 | 查找元素最后一次出现的索引 |
find() | let element = arr.find(element => condition) | 否 | 元素值或 undefined | 查找符合条件的第一个元素 |
findIndex() | let index = arr.findIndex(element => condition) | 否 | 索引值或 -1 | 查找符合条件的第一个元素的索引 |
includes() | let result = arr.includes(targetElement) | 否 | 布尔值,true 或 false | 判断数组是否包含某个元素 |
五、数组排序与反转方法
| 方法 | 使用示例 | 是否改变原数组 | 返回值 | 作用 |
|---|---|---|---|---|
sort() | arr.sort((a, b) => a - b) | 是 | 原数组 | 对数组元素排序 |
reverse() | arr.reverse() | 是 | 原数组 | 反转数组元素顺序 |
六、数组归约方法
| 方法 | 使用示例 | 是否改变原数组 | 返回值 | 作用 |
|---|---|---|---|---|
reduce() | let result = arr.reduce((acc, curr) => acc + curr, initialValue) | 否 | 累加结果 | 数组元素累加 |
reduceRight() | let result = arr.reduceRight((acc, curr) => acc + curr, initialValue) | 否 | 累加结果 | 数组元素从右往左累加 |
七、数组转换为字符串方法
| 方法 | 使用示例 | 是否改变原数组 | 返回值 | 作用 |
|---|---|---|---|---|
join() | let str = arr.join(separator) | 否 | 字符串 | 将数组元素连接为字符串 |
split() | let arr = str.split('') | 不改变字符串 | 数组 | 将字符串分割为数组 |