返回
一把 JavaScript Array 特技小窍门合集助你成为Array Manipulation Master
前端
2023-12-24 01:02:12
日常开发中,数组操作是不可避免的,为了方便查找与回顾,将数组操作技巧归纳整理成此文。
无论是常见的求和、排序、取最大值等,还是扩展的清空数组、扁平化、去重、合并、重组等,都将为你一一奉上,慢慢食用~
基础篇
1. 求和
求和是数组操作中最基本的操作之一,可以使用 reduce() 方法轻松实现:
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // 15
2. 排序
排序是数组操作中的另一个基本操作,可以使用 sort() 方法实现。sort() 方法可以根据某个排序规则对数组中的元素进行排序,默认情况下是按照升序排列:
const numbers = [1, 5, 3, 2, 4];
numbers.sort();
console.log(numbers); // [1, 2, 3, 4, 5]
如果想要按照降序排列,可以传递一个比较函数作为参数:
numbers.sort((a, b) => b - a);
console.log(numbers); // [5, 4, 3, 2, 1]
3. 取最大值
取最大值可以使用 Math.max() 方法实现:
const numbers = [1, 2, 3, 4, 5];
const max = Math.max(...numbers);
console.log(max); // 5
4. 取最小值
取最小值可以使用 Math.min() 方法实现:
const numbers = [1, 2, 3, 4, 5];
const min = Math.min(...numbers);
console.log(min); // 1
扩展篇
1. 清空数组
可以使用以下几种方法清空数组:
- 使用 length 属性:
const numbers = [1, 2, 3, 4, 5];
numbers.length = 0;
console.log(numbers); // []
- 使用 splice() 方法:
const numbers = [1, 2, 3, 4, 5];
numbers.splice(0, numbers.length);
console.log(numbers); // []
- 使用 pop() 方法:
const numbers = [1, 2, 3, 4, 5];
while (numbers.length > 0) {
numbers.pop();
}
console.log(numbers); // []
2. 扁平化数组
可以使用以下几种方法扁平化数组:
- 使用 reduce() 方法:
const array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
const flatArray = array.reduce((accumulator, currentValue) => accumulator.concat(currentValue), []);
console.log(flatArray); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
- 使用 flat() 方法:
const array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
const flatArray = array.flat();
console.log(flatArray); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
3. 去重数组
可以使用以下几种方法去重数组:
- 使用 Set 对象:
const numbers = [1, 2, 3, 4, 5, 1, 2, 3];
const uniqueNumbers = [...new Set(numbers)];
console.log(uniqueNumbers); // [1, 2, 3, 4, 5]
- 使用 filter() 方法:
const numbers = [1, 2, 3, 4, 5, 1, 2, 3];
const uniqueNumbers = numbers.filter((value, index, self) => self.indexOf(value) === index);
console.log(uniqueNumbers); // [1, 2, 3, 4, 5]
4. 合并数组
可以使用以下几种方法合并数组:
- 使用 concat() 方法:
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const mergedArray = array1.concat(array2);
console.log(mergedArray); // [1, 2, 3, 4, 5, 6]
- 使用 spread 操作符:
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const mergedArray = [...array1, ...array2];
console.log(mergedArray); // [1, 2, 3, 4, 5, 6]
5. 重组数组
可以使用以下几种方法重组数组:
- 使用 slice() 方法:
const array = [1, 2, 3, 4, 5];
const reversedArray = array.slice().reverse();
console.log(reversedArray); // [5, 4, 3, 2, 1]
- 使用 sort() 方法:
const array = [1, 2, 3, 4, 5];
const reversedArray = array.sort((a, b) => b - a);
console.log(reversedArray); // [5, 4, 3, 2, 1]
总结
本文汇总了 JavaScript Array 的各种奇技淫巧,涵盖基础和扩展两大篇章,包括常见求和、排序、取最大值等,还有扩展的清空数组、扁平化、去重、合并、重组等,希望对你有帮助!