JavaScript 数组方法全解析

509 阅读8分钟

数组是 JavaScript 中最基本且最常用的数据结构之一。它提供了丰富的方法来操作和处理数组中的数据。本文将详细介绍 JavaScript 中所有的数组方法,并通过示例代码帮助你更好地理解和使用它们。

一、数组的构造方法

1.Array.of()

Array.of()方法用于创建一个新数组实例,其参数会直接作为数组的元素,而不会像Array()那样根据参数数量和类型进行特殊处理。

const arr1 = Array.of(1, 2, 3); // [1, 2, 3]
const arr2 = Array.of(1);       // [1]
const arr3 = Array.of();        // []

2.Array.from()

Array.from()方法用于从类数组对象或可迭代对象创建一个新的数组实例。

const arrayLike = { 0: "a", 1: "b", length: 2 };
const arr1 = Array.from(arrayLike); // ["a", "b"]

const set = new Set(["a", "b", "c"]);
const arr2 = Array.from(set);       // ["a", "b", "c"]

二、数组的添加和删除方法

1.push()

push()方法将一个或多个元素添加到数组的末尾,并返回新数组的长度。

const arr = [1, 2, 3];
const newLength = arr.push(4); // arr: [1, 2, 3, 4], newLength: 4

2.pop()

pop()方法移除数组的最后一个元素,并返回被移除的元素。

const arr = [1, 2, 3];
const removedElement = arr.pop(); // arr: [1, 2], removedElement: 3

3.shift()

shift()方法移除数组的第一个元素,并返回被移除的元素。

const arr = [1, 2, 3];
const removedElement = arr.shift(); // arr: [2, 3], removedElement: 1

4.unshift()

unshift()方法将一个或多个元素添加到数组的开头,并返回新数组的长度。

const arr = [1, 2, 3];
const newLength = arr.unshift(0); // arr: [0, 1, 2, 3], newLength: 4

5.splice()

splice()方法用于添加或删除数组中的元素。它接受多个参数,第一个参数是开始操作的索引,第二个参数是要删除的元素数量,后续参数是要插入的元素。

const arr = [1, 2, 3, 4, 5];
arr.splice(2, 1, "a", "b"); // arr: [1, 2, "a", "b", 4, 5]

三、数组的查找方法

1.indexOf()

indexOf()方法返回指定元素在数组中的第一个索引,如果不存在则返回-1

const arr = [1, 2, 3];
const index = arr.indexOf(2); // index: 1

2.lastIndexOf()

lastIndexOf()方法返回指定元素在数组中的最后一个索引,如果不存在则返回-1

const arr = [1, 2, 3, 2];
const index = arr.lastIndexOf(2); // index: 3

3.find()

find()方法返回数组中满足条件的第一个元素,如果没有找到则返回undefined

const arr = [1, 2, 3, 4];
const found = arr.find((element) => element > 2); // found: 3

4.findIndex()

findIndex()方法返回数组中满足条件的第一个元素的索引,如果没有找到则返回-1

const arr = [1, 2, 3, 4];
const index = arr.findIndex((element) => element > 2); // index: 2

5.includes()

includes()方法检查数组是否包含指定的元素,返回布尔值。

const arr = [1, 2, 3];
const hasElement = arr.includes(2); // hasElement: true

四、数组的遍历方法

1.forEach()

forEach()方法对数组中的每个元素执行一次给定的函数。

const arr = [1, 2, 3];
arr.forEach((element) => {
    console.log(element); // 输出:1, 2, 3
});

2.map()

map()方法创建一个新数组,其元素是调用一次提供的函数后的返回值。

const arr = [1, 2, 3];
const newArr = arr.map((element) => element * 2); // newArr: [2, 4, 6]

3.filter()

filter()方法创建一个新数组,包含通过测试的所有元素。

const arr = [1, 2, 3, 4];
const newArr = arr.filter((element) => element > 2); // newArr: [3, 4]

4.reduce()

reduce()方法对数组中的每个元素执行一个由左到右的累加器函数,将其结果汇总为单个返回值。

const arr = [1, 2, 3, 4];
const sum = arr.reduce((accumulator, currentValue) => accumulator + currentValue, 0); // sum: 10

5.reduceRight()

reduceRight()方法与reduce()类似,但累加器函数是从数组的末尾开始执行。

const arr = [1, 2, 3, 4];
const sum = arr.reduceRight((accumulator, currentValue) => accumulator + currentValue, 0); // sum: 10

五、数组的排序方法

1.sort()

sort()方法对数组的元素进行排序,并返回排序后的数组。默认排序是按照字符串的 Unicode 码位值进行排序。

const arr = [3, 1, 2];
arr.sort(); // arr: [1, 2, 3]

如果需要按照数字大小排序,可以传入一个比较函数:

const arr = [3, 1, 2];
arr.sort((a, b) => a - b); // arr: [1, 2, 3]

六、数组的合并与分割方法

1.concat()

concat()方法用于合并两个或多个数组,返回一个新数组。

const arr1 = [1, 2];
const arr2 = [3, 4];
const newArr = arr1.concat(arr2); // newArr: [1, 2, 3, 4]

2.slice()

slice()方法返回一个从开始到结束(不包括结束)选择的数组的一部分浅拷贝到一个新数组对象。

const arr = [1, 2, 3, 4];
const newArr = arr.slice(1, 3); // newArr: [2, 3]

3.join()

join()方法将数组的所有元素连接成一个字符串。

const arr = [1, 2, 3];
const str = arr.join(", "); // str: "1, 2, 3"

4.toString()

toString()方法将数组转换为字符串。

const arr = [1, 2, 3];
const str = arr.toString(); // str: "1,2,3"

七、数组的反转方法

1.reverse()

reverse()方法将数组中的元素顺序颠倒,并返回该数组。

const arr = [1, 2, 3];
arr.reverse(); // arr: [3, 2, 1]

八、数组的拷贝方法

1.slice()

slice()方法可以用于浅拷贝数组。

const arr = [1, 2, 3];
const newArr = arr.slice(); // newArr: [1, 2, 3]

2.concat()

concat()方法也可以用于浅拷贝数组。

const arr = [1, 2, 3];
const newArr = arr.concat(); // newArr: [1, 2, 3]

九、数组的填充方法

1.fill()

fill()方法用于将数组的指定部分填充为一个静态值。它接受三个参数:填充的值、起始索引(默认为0)和结束索引(默认为数组长度)。

const arr = [1, 2, 3, 4, 5];
arr.fill(0, 2, 4); // arr: [1, 2, 0, 0, 5]

十、数组的解构方法

1.解构赋值

解构赋值是一种从数组中提取值并赋给变量的简洁方式。它支持默认值和嵌套解构。

const arr = [1, 2, 3];
const [a, b, c] = arr; // a: 1, b: 2, c: 3

const [x, , y] = arr; // x: 1, y: 3

const [p = 0, q = 0] = []; // p: 0, q: 0

const [m, [n, o]] = [1, [2, 3]]; // m: 1, n: 2, o: 3

十一、数组的迭代器方法

1.entries()

entries()方法返回一个新的数组迭代器对象,该对象包含数组中每个索引的键/值对。

const arr = [1, 2, 3];
const iterator = arr.entries();

console.log(iterator.next().value); // {0: 1}
console.log(iterator.next().value); // {1: 2}
console.log(iterator.next().value); // {2: 3}

2.keys()

keys()方法返回一个新的数组迭代器对象,该对象包含数组中每个索引的键。

const arr = [1, 2, 3];
const iterator = arr.keys();

console.log(iterator.next().value); // 0
console.log(iterator.next().value); // 1
console.log(iterator.next().value); // 2

3.values()

values()方法返回一个新的数组迭代器对象,该对象包含数组中每个索引的值。

const arr = [1, 2, 3];
const iterator = arr.values();

console.log(iterator.next().value); // 1
console.log(iterator.next().value); // 2
console.log(iterator.next().value); // 3

4.for...of循环

for...of循环可以用来遍历数组的值,结合entries()keys()values()方法,可以实现更灵活的遍历。

const arr = [1, 2, 3];

for (const value of arr) {
    console.log(value); // 输出:1, 2, 3
}

for (const [key, value] of arr.entries()) {
    console.log(key, value); // 输出:0 1, 1 2, 2 3
}

十二、数组的其他实用方法

1.copyWithin()

copyWithin()方法将数组的一部分复制到同一数组中的另一个位置,并返回该数组。它不会改变数组的长度。

const arr = [1, 2, 3, 4, 5];
arr.copyWithin(0, 3); // arr: [4, 5, 3, 4, 5]

2.flat()flatMap()

flat()方法会按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回。

const arr = [1, [2, [3, [4, 5]]]];
const newArr = arr.flat(Infinity); // newArr: [1, 2, 3, 4, 5]

flatMap()方法先对数组中的每个元素调用一次提供的映射函数,然后将结果通过flat()方法展平一层,最后返回一个新数组。

const arr = [1, 2, 3];
const newArr = arr.flatMap((x) => [x, x * 2]); // newArr: [1, 2, 2, 4, 3, 6]

十三、数组方法的性能优化

1.避免频繁修改数组长度

频繁修改数组长度(如使用length属性)会导致性能问题,因为每次修改长度时,浏览器可能需要重新分配内存。

const arr = [];
for (let i = 0; i < 1000000; i++) {
    arr.push(i); // 推荐:动态添加元素
}
// 避免:arr.length = 1000000;

2.使用Array.from()替代循环

如果需要从类数组对象或可迭代对象创建数组,Array.from()方法通常比手动循环更高效。

const arrayLike = { 0: "a", 1: "b", length: 2 };
const arr = Array.from(arrayLike); // ["a", "b"]

3.使用map()filter()替代循环

map()filter()方法是函数式编程的常用工具,它们通常比手动循环更简洁且性能更好。

const arr = [1, 2, 3, 4];
const doubled = arr.map((x) => x * 2); // [2, 4, 6, 8]
const even = arr.filter((x) => x % 2 === 0); // [2, 4]

4.使用reduce()替代多层循环

reduce()方法可以将多层循环逻辑简化为单层循环,从而提高代码的可读性和性能。

const arr = [[1, 2], [3, 4], [5, 6]];
const flattened = arr.reduce((acc, val) => acc.concat(val), []); // [1, 2, 3, 4, 5, 6]

十四、总结

JavaScript 数组提供了丰富的方法来操作和处理数组数据。本文详细介绍了数组的构造方法、添加和删除方法、查找方法、遍历方法、排序方法、合并与分割方法、反转方法、拷贝方法、填充方法、解构方法、迭代器方法以及其他实用方法。通过这些方法,我们可以高效地处理数组数据,实现各种复杂的逻辑。

在实际开发中,合理选择和使用数组方法可以提高代码的可读性和性能。同时,了解每种方法的适用场景和性能特点,可以帮助我们写出更高效的代码。

如果你对数组方法还有其他疑问,或者有更多实用的技巧,欢迎在评论区留言,我们一起探讨!