JavaScript 数组方法详解
1. map
- 作用:对数组中的每个元素执行指定的回调函数,返回一个新数组,新数组的长度与原数组一致。
- 语法:
array.map((element, index, array) => { /* ... */ });
- 示例:
let numbers = [1, 2, 3];
let doubled = numbers.map(x => x * 2);
console.log(doubled); // 输出 [2, 4, 6]
2. filter
- 作用:过滤数组元素,返回所有符合条件的元素组成的新数组。
- 语法:
array.filter((element, index, array) => { /* ... */ });
- 示例:
let numbers = [1, 2, 3, 4, 5];
let even = numbers.filter(x => x % 2 === 0);
console.log(even); // 输出 [2, 4]
3. some
- 作用:测试数组中是否至少有一个元素满足条件,返回 true 或 false。
- 语法:
array.some((element, index, array) => { /* ... */ });
- 示例:
let numbers = [1, 2, 3];
let hasEven = numbers.some(x => x % 2 === 0);
console.log(hasEven); // 输出 true
4. every
- 作用:测试数组中是否所有元素都满足条件,返回 true 或 false。
- 语法:
array.every((element, index, array) => { /* ... */ });
- 示例:
let numbers = [2, 4, 6];
let allEven = numbers.every(x => x % 2 === 0);
console.log(allEven); // 输出 true
5. reduce
- 作用:累加数组元素,返回一个最终结果。
- 语法:
array.reduce((accumulator, currentValue, index, array) => { /* ... */ }, initialValue);
- 示例:
let numbers = [1, 2, 3, 4];
let sum = numbers.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // 输出 10
6. find
- 作用:返回数组中第一个满足条件的元素,找不到返回 undefined。
- 语法:
array.find((element, index, array) => { /* ... */ });
- 示例:
let numbers = [1, 2, 3, 4];
let firstEven = numbers.find(x => x % 2 === 0);
console.log(firstEven); // 输出 2
7. findIndex
- 作用:返回第一个满足条件的元素的索引,找不到返回 -1。
- 语法:
array.findIndex((element, index, array) => { /* ... */ });
- 示例:
let numbers = [1, 2, 3, 4];
let index = numbers.findIndex(x => x > 3);
console.log(index); // 输出 3
8. forEach
- 作用:对数组的每个元素执行指定的回调函数(不会返回值)。
- 语法:
array.forEach((element, index, array) => { /* ... */ });
- 示例:
let numbers = [1, 2, 3];
numbers.forEach(x => console.log(x * 2));
// 输出:
// 2
// 4
// 6
9. includes
- 作用:检查数组中是否包含某个值,返回 true 或 false。
- 语法:
array.includes(valueToFind, startIndex);
- 示例:
let numbers = [1, 2, 3];
console.log(numbers.includes(2)); // 输出 true
console.log(numbers.includes(4)); // 输出 false
10. sort
- 作用:对数组进行排序(默认按字符串 Unicode 顺序)。
- 语法:
array.sort((a, b) => { /* ... */ });
- 示例: 默认排序:
let numbers = [3, 1, 4, 2];
console.log(numbers.sort()); // 输出 [1, 2, 3, 4]
自定义排序(按大小升序):
let numbers = [3, 1, 4, 2];
console.log(numbers.sort((a, b) => a - b)); // 输出 [1, 2, 3, 4]
11. concat
- 作用:连接多个数组,返回新数组。
- 语法:
array.concat(value1, value2, ...);
- 示例:
let arr1 = [1, 2];
let arr2 = [3, 4];
let combined = arr1.concat(arr2);
console.log(combined); // 输出 [1, 2, 3, 4]
12. slice
- 作用:从数组中提取部分元素,返回新数组(不改变原数组)。
- 语法:
array.slice(start, end);
- 示例:
let numbers = [1, 2, 3, 4, 5];
console.log(numbers.slice(1, 3)); // 输出 [2, 3]
13. splice
- 作用:添加、删除或替换数组中的元素(会修改原数组)。
- 语法:
array.splice(start, deleteCount, item1, item2, ...);
- 示例:
let numbers = [1, 2, 3, 4];
numbers.splice(1, 2, 99, 100);
console.log(numbers); // 输出 [1, 99, 100, 4]