这么多的数组方法,有你不知道的吗

103 阅读5分钟

image.png

在前端开发中,JavaScript数组是不可或缺的数据结构之一。熟练掌握数组方法可以提高代码的可读性和性能。本文将介绍JavaScript中的常用的数组方法。

1. map() - 映射新数组

const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6]

2. filter() - 过滤元素

const numbers = [1, 2, 3, 4, 5];
const even = numbers.filter(num => num % 2 === 0);
console.log(even); // [2, 4]

3. reduce() - 累加元素

const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // 15

4. forEach() - 遍历数组

const colors = ['red', 'blue', 'green'];
colors.forEach(color => console.log(color));

5. find() - 查找元素

const users = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }];
const user = users.find(u => u.id === 2);
console.log(user); // { id: 2, name: 'Bob' }

6. some() - 检查是否有满足条件的元素

const ages = [25, 30, 18, 15];
const isAdult = ages.some(age => age >= 18);
console.log(isAdult); // true

7. every() - 检查是否所有元素满足条件

const numbers = [2, 4, 6, 8];
const allEven = numbers.every(num => num % 2 === 0);
console.log(allEven); // true

8. flat() - 扁平化嵌套数组

const nestedArray = [1, [2, 3], [4, [5]]];
const flatArray = nestedArray.flat(2);
console.log(flatArray); // [1, 2, 3, 4, 5]

9. from() - 从类数组对象创建数组

const nodeList = document.querySelectorAll('p');
const paragraphArray = Array.from(nodeList);
console.log(paragraphArray);

10. indexOf() - 查找元素的索引

const colors = ['red', 'blue', 'green'];
const index = colors.indexOf('blue');
console.log(index); // 1

11. lastIndexOf() - 查找元素的最后一个索引

const numbers = [1, 2, 3, 2, 4, 5, 2];
const lastIndex = numbers.lastIndexOf(2);
console.log(lastIndex); // 6

12. includes() - 检查数组是否包含元素

const fruits = ['apple', 'banana', 'cherry'];
const hasBanana = fruits.includes('banana');
console.log(hasBanana); // true

13. splice() - 修改原数组

const numbers = [1, 2, 3, 4, 5];
numbers.splice(2, 1, 6);
console.log(numbers); // [1, 2, 6, 4, 5]

14. slice() - 创建原数组的浅拷贝

const colors = ['red', 'blue', 'green'];
const copy = colors.slice();
console.log(copy); // ['red', 'blue', 'green']

15. push() - 向数组末尾添加元素

const numbers = [1, 2, 3];
numbers.push(4);
console.log(numbers); // [1, 2, 3, 4]

16. pop() - 移除数组末尾元素

const numbers = [1, 2, 3];
const removed = numbers.pop();
console.log(removed); // 3

17. shift() - 移除数组首位元素

const colors = ['red', 'blue', 'green'];
const removed = colors.shift();
console.log(removed); // 'red'

18. unshift() - 向数组首位添加元素

const colors = ['blue', 'green'];
colors.unshift('red');
console.log(colors); // ['red', 'blue', 'green']

19. concat() - 合并多个数组

const arr1 = [1, 2];
const arr2 = [3, 4];
const merged = arr1.concat(arr2);
console.log(merged); // [1, 2, 3, 4]

20. join() - 将数组元素连接成字符串

const fruits = ['apple', 'banana', 'cherry'];
const joined = fruits.join(', ');
console.log(joined); // 'apple, banana, cherry'

21. sort() - 排序数组

const numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5];
numbers.sort();
console.log(numbers); // [1, 1, 2, 3, 4, 5, 5, 6, 9]

22. reverse() - 颠倒数组元素顺序

const colors = ['red', 'blue', 'green'];
colors.reverse();
console.log(colors); // ['green', 'blue', 'red']

23. fill() - 填充数组元素

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

24. copyWithin() - 复制元素到指定位置

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

25. findIndex() - 查找元素的索引

const numbers = [1, 2, 3, 4, 5];
const index = numbers.findIndex(num => num > 3);
console.log(index); // 3

26. keys() - 获取数组索引的迭代器

const colors = ['red', 'blue', 'green'];
const iterator = colors.keys();
for (const index of iterator) {
  console.log(index); // 0, 1, 2
}

27. values() - 获取数组值的迭代器

const colors = ['red', 'blue', 'green'];
const iterator = colors.values();
for (const value of iterator) {
  console.log(value); // red, blue, green
}

28. entries() - 获取索引和值的迭代器

const colors = ['red', 'blue', 'green'];
const iterator = colors.entries();
for (const [index, value] of iterator) {
  console.log(`Index: ${index}, Value: ${value}`);
}

29. flatMap() - 映射并扁平化数组

const sentences = ['Hello, world!', 'Goodbye, cruel world!'];
const words = sentences.flatMap(sentence => sentence.split(' '));
console.log(words); // ['Hello,', 'world!', 'Goodbye,', 'cruel', 'world!']

30. reduceRight() - 从右向左累加元素

const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduceRight((acc, num) => acc + num, 0);
console.log(sum); // 15

31. at() - 获取数组最后一个元素

const colors = ['red', 'blue', 'green'];
const lastColor = colors.at(-1);
console.log(lastColor); // 'green'

32. new Set() - 去重数组元素

const numbers = [1, 2, 2, 3, 3, 4];
const uniqueNumbers = [...new Set(numbers)];
console.log(uniqueNumbers); // [1, 2, 3, 4]

数组方法混合使用场景:

1. 统计元素出现次数

const colors = ['red', 'blue', 'red', 'green', 'blue'];
const countRed = colors.filter(color => color === 'red').length;
console.log(countRed); // 2

2. 拆分数组

const numbers = [1, 2, 3, 4, 5];
const [even, odd] = numbers.reduce(
  (acc, num) => (num % 2 === 0 ? acc[0].push(num) : acc[1].push(num), acc),
  [[], []]
);
console.log('Even:', even);
console.log('Odd:', odd);

3. 拆分数组成多个块

const numbers = [1, 2, 3, 4, 5, 6, 7, 8];
function chunkArray(array, size) {
  return Array.from({ length: Math.ceil(array.length / size) }, (v, i) =>
    array.slice(i * size, i * size + size)
  );
}
const chunks = chunkArray(numbers, 3);
console.log(chunks); // [[1,2,3], [4,5,6], [7,8]]

4.合并多个数组

const names = ['Alice', 'Bob', 'Charlie'];
const ages = [25, 30, 35];
const zipped = names.map((name, index) => [name, ages[index]]);
console.log(zipped); // [['Alice', 25], ['Bob', 30], ['Charlie', 35]]

5.求两个数组的差集

const array1 = [1, 2, 3, 4, 5];
const array2 = [3, 4, 5, 6, 7];
const diff = array1.filter(item => !array2.includes(item));
console.log(diff); // [1, 2]

6.求两个数组的交集

const array1 = [1, 2, 3, 4, 5];
const array2 = [3, 4, 5, 6, 7];
const intersection = array1.filter(item => array2.includes(item));
console.log(intersection); // [3, 4, 5]

7.求两个数组的并集

const array1 = [1, 2, 3, 4, 5];
const array2 = [3, 4, 5, 6, 7];
const union = [...new Set([...array1, ...array2])];
console.log(union); // [1, 2, 3, 4, 5, 6, 7]

8.根据属性去重对象数组

const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 1, name: 'Alice' },
];
const uniqueUsers = Array.from(
  new Map(users.map(user => [user.id, user])).values()
);
console.log(uniqueUsers);

9.随机打乱数组顺序

const numbers = [1, 2, 3, 4, 5];
const shuffled = numbers.sort(() => Math.random() - 0.5);
console.log(shuffled);

10.矩阵转置

const matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
const transposed = matrix[0].map((col, i) => matrix.map(row => row[i]));
console.log(transposed);

11.根据大小拆分数组

function chunkBySize(array, size) {
  return array.reduce((acc, value, index) => {
    if (index % size === 0) acc.push([]);
    acc[acc.length - 1].push(value);
    return acc;
  }, []);
}

const numbers = [1, 2, 3, 4, 5, 6, 7, 8];
const chunked = chunkBySize(numbers, 3);
console.log(chunked);

12.根据条件求差集

const array1 = [{ id: 1 }, { id: 2 }, { id: 3 }];
const array2 = [{ id: 2 }];
const diff = array1.filter(item1 => !array2.some(item2 => item1.id === item2.id));
console.log(diff);

13.根据条件求交集

const array1 = [{ id: 1 }, { id: 2 }, { id: 3 }];
const array2 = [{ id: 2 }, { id: 3 }];
const intersection = array1.filter(item1 => array2.some(item2 => item1.id === item2.id));
console.log(intersection);

14.根据条件求并集

const array1 = [{ id: 1 }, { id: 2 }, { id: 3 }];
const array2 = [{ id: 2 }, { id: 3 }, { id: 4 }];
const union = array1.concat(array2.filter(item2 => !array1.some(item1 => item1.id === item2.id));
console.log(union);

15.根据条件找到最小元素

const students = [
  { name: 'Alice', age: 22 },
  { name: 'Bob', age: 18 },
  { name: 'Charlie', age: 20 },
];
const youngestStudent = students.reduce((min, student) =>
  student.age < min.age ? student : min
);
console.log(youngestStudent);