# ES6之数组的扩展
# 一. 扩展运算符(常用)
扩展运算符是三个点...
, 可以将一个数组转为用逗号分隔的参数序列
console.log(...[1, 2, 3])
// 1 2 3
console.log(1, ...[2, 3, 4], 5)
// 1 2 3 4 5
// 用于函数调用
function add(x, y) {
return x + y;
}
const numbers = [1, 2];
add(...numbers) // 3
// 扩展运算符后面还可以放置表达式
const arr = [...(x > 0 ? ['a'] : []), 'b'];
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
注意点
- 扩展运算符后面是一个空数组,不产生任何效果
[...[], 1]
// [1]
2
- 只有函数调用时,扩展运算符才可以放在圆括号中,否则会报错
(...[1, 2])
// Uncaught SyntaxError: Unexpected number
console.log((...[1, 2]))
// Uncaught SyntaxError: Unexpected number
console.log(...[1, 2])
// 1 2
2
3
4
5
6
7
8
# 使用
- 替代函数的 apply() 方法 ,将数组转为函数的参数
// ES5 的写法
Math.max.apply(null, [14, 3, 77])
// ES6 的写法
Math.max(...[14, 3, 77])
// 等同于
Math.max(14, 3, 77);
2
3
4
5
6
7
8
- 复制数组
const a1 = [1, 2];
// 写法一
const a2 = [...a1];
// 写法二
const [...a2] = a1;
// 上面的两种写法,a2都是a1的克隆。
2
3
4
5
6
7
- 合并数组
const arr1 = ['a', 'b'];
const arr2 = ['c'];
const arr3 = ['d', 'e'];
// ES5 的合并数组
arr1.concat(arr2, arr3);
// [ 'a', 'b', 'c', 'd', 'e' ]
// ES6 的合并数组
[...arr1, ...arr2, ...arr3]
// [ 'a', 'b', 'c', 'd', 'e' ]
2
3
4
5
6
7
8
9
10
11
- 与解构赋值结合
const [first, ...rest] = [1, 2, 3, 4, 5];
first // 1
rest // [2, 3, 4, 5]
const [first, ...rest] = [];
first // undefined
rest // []
const [first, ...rest] = ["foo"];
first // "foo"
rest // []
2
3
4
5
6
7
8
9
10
11
- 字符串
[...'hello']
// [ "h", "e", "l", "l", "o" ]
2
- 实现了 Iterator 接口的对象 任何定义了遍历器(Iterator)接口的对象,都可以用扩展运算符转为真正的数组。
let nodeList = document.querySelectorAll('div');
let array = [...nodeList];
2
# 二. Array.from() (常用)
Array.from()
方法用于将两类对象转为真正的数组:类似数组的对象(如arguments参数) 和可遍历(iterable)的对象(包括 ES6 新增的数据结构 Set
和 Map
)。
let arrayLike = {
'0': 'a',
'1': 'b',
'2': 'c',
length: 3
};
// ES5 的写法
var arr1 = [].slice.call(arrayLike); // ['a', 'b', 'c']
// ES6 的写法
let arr2 = Array.from(arrayLike); // ['a', 'b', 'c']
// arguments 对象
function foo() {
// ES5
const args = [].slice.call(arguments);
// ES6
const args = Array.from(arguments);
const args = [...arguments];
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 三. Array.of()
Array.of()方法用于将一组值,转换为数组。
Array.of(3, 11, 8) // [3,11,8]
Array.of(3) // [3]
Array.of(3).length // 1
2
3
# 四. 实例方法: includes() (常用)
该方法返回一个布尔值,表示某个数组是否包含给定的值,与字符串的includes
方法类似。
[1, 2, 3].includes(2) // true
[1, 2, 3].includes(4) // false
[1, 2, NaN].includes(NaN) // true
2
3
该方法的第二个参数表示搜索的起始位置,默认为0。如果第二个参数为负数,则表示倒数的位置,如果这时它大于数组长度(比如第二个参数为-4,但数组长度为3),则会重置为从0开始。
[1, 2, 3].includes(3, 3); // false
[1, 2, 3].includes(3, -1); // true
2
# 五. 实例方法:find(),findIndex(),findLast(),findLastIndex() (常用)
find()
方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined。
// 语法: 回调函数可以接受三个参数,依次为当前的值、当前的位置和原数组
find(function(element, index, array) { /* … */ }, thisArg)`
// 示例1
const a = [1, 4, -5, 10].find((n) => n < 0) // -5
// 示例2
[1, 5, 10, 15].findIndex(function(value, index, arr) {
return value > 9;
}) // 2
// 示例3
let person = {name: 'John', age: 20};
[10, 12, 26, 15].find(function(value, index, arr) {
return value > 9;
}, person);
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
上面的示例3代码中,find()函数接收了第二个参数person对象,回调函数中的this对象指向person对象。
findIndex()
方法的用法与find()
方法类似,返回第一个符合条件的数组成员的位置,如果所有成员都不符合条件,则返回-1。
find()
和findIndex()
都是从数组的0号位,依次向后检查。ES2022 新增了两个方法findLast()
和findLastIndex()
,从数组的最后一个成员开始,依次向前检查,其他都保持不变。
# 六. 实例方法:entries(),keys() 和 values() (常用)
用于遍历数组。它们都返回一个遍历器对象,可以用for...of循环进行遍历,唯一的区别是keys()是对键名的遍历、values()是对键值的遍历,entries()是对键值对的遍历。
for (let index of ['a', 'b'].keys()) {
console.log(index);
}
// 0
// 1
for (let elem of ['a', 'b'].values()) {
console.log(elem);
}
// 'a'
// 'b'
for (let [index, elem] of ['a', 'b'].entries()) {
console.log(index, elem);
}
// 0 "a"
// 1 "b"
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 七. 实例方法:fill()
该方法使用给定值,填充一个数组。
['a', 'b', 'c'].fill(7)
// [7, 7, 7]
new Array(3).fill(7)
// [7, 7, 7]
2
3
4
5
fill方法还可以接受第二个和第三个参数,用于指定填充的起始位置和结束位置。
['a', 'b', 'c'].fill(7, 1, 2)
// ['a', 7, 'c']
2
# 八. 实例方法:at()
Array.prototype.flat()
返回对应位置的成员,并支持负索引
const sentence = 'This is a sample sentence';
sentence.at(0); // 'T'
sentence.at(-1); // 'e'
//如果参数位置超出了数组范围,at()返回undefined
sentence.at(-100) // undefined
sentence.at(100) // undefined
2
3
4
5
6
7
8
# 九. 实例方法:copyWithin()
该方法浅复制数组的一部分到同一数组中的另一个位置,并返回它,不会改变原数组的长度。
// 语法
Array.prototype.copyWithin(target, start = 0, end = this.length)
2
参数
target(必需):从该位置开始替换数据。如果为负值,表示倒数。
start(可选):从该位置开始读取数据,默认为 0。如果为负值,表示从末尾开始计算。
end(可选):到该位置前停止读取数据,默认等于数组长度。如果为负值,表示从末尾开始计算。
// 将3号位复制到0号位
[1, 2, 3, 4, 5].copyWithin(0, 3, 4)
// [4, 2, 3, 4, 5]
// -2相当于3号位,-1相当于4号位
[1, 2, 3, 4, 5].copyWithin(0, -2, -1)
// [4, 2, 3, 4, 5]
// 将3号位复制到0号位
[].copyWithin.call({length: 5, 3: 1}, 0, 3)
// {0: 1, 3: 1, length: 5}
2
3
4
5
6
7
8
9
10
11