容易混淆的数组方法总结

Javascript 中的数组实际上是对象的一个子类型

1
2
new Array instanceof Array  // true
new Array instanceof Object // true

Array.prototype.slice() VS Array.prototype.splice()

方法 Array.prototype.slice() Array.prototype.splice()
参数 start[, end] start[, deleteCount[, item1[, item2[, …]]]]
return 一个含有提取元素的新数组「包含 start,但不包含 end」 由被删除的元素组成的数组
对原数组影响 无影响 有影响
描述 抽取当前数组中的一段元素组合成一个新数组「浅拷贝」 在任意的位置给数组添加或删除任意个元素

Array.prototype.slice() 语法

1
2
3
4
5
6
7
8
array.slice();
// [0, end] -> 可用来实现数组⚠️浅拷贝⚠️

array.slice(start);
// [start, end]

array.slice(start, end);
// [start, end) -> 包含 start,但不包含 end

Array.prototype.splice() 语法

1
2
3
4
5
6
7
8
array.splice(start);
// 从 start 位置开始删除 [start, end] 的元素

array.splice(start, deleteCount);
// 从 start 位置开始删除 [start, Count] 的元素

array.splice(start, 0, item1, item2, ...);
// 从 start 位置开始添加 item1, item2, ... 元素

Array() VS Array.of() VS Array.from()

  • Array(): Array 构造器
  • Array.of(): 创建一个具有可变数量参数的新数组实例,而不考虑参数的数量或类型
  • Array.from(): 从一个类似数组或可迭代对象中创建一个新的数组实例
1
2
3
4
5
6
7
8
9
Array(7);          // [ , , , , , , ]
Array(1, 2, 3); // [1, 2, 3]

Array.of(7); // [7]
Array.of(1, 2, 3); // [1, 2, 3]

Array.from(7); // []
Array.from({ length: 7 }); // [undefined, undefined, undefined, undefined, undefined, undefined, undefined]
Array.from({ length: 7 }, (k, v) => v); // [0, 1, 2, 3, 4, 5, 6]

对象数组排序

1
2
3
4
5
6
7
8
9
const compare = key => (a, b) => a[key] - b[key];

const array = [
{ key: 2, value: 'b' },
{ key: 3, value: 'c' },
{ key: 1, value: 'a' }
];
console.log(array.sort(compare('key')));
// [{ key: 1, value: 'a' }, { key: 2, value: 'b' }, { key: 3, value: 'c' }]
方法 参数 return 是否原数组影响
filter currentValue[, index, arr] 新数组 无影响
map currentValue[, index, arr] 新数组 无影响
reduce total, currentValue[, index, arr] total 无影响
forEach currentValue[, index, arr]
some currentValue[, index, arr] Boolean 无影响