JS数组的扩展
数组的扩展
扩展运算符
…
扩展运算符(spread)是三个点(…
)。它好比 rest 参数的逆运算,将一个数组转为用逗号分隔的参数序列。
1
2
3
4
5
6
7
8
console.log(...[1, 2, 3])
// 1 2 3
console.log(1, ...[2, 3, 4], 5)
// 1 2 3 4 5
[...document.querySelectorAll('div')]
// [<div>, <div>, <div>]
该运算符主要用于函数调用:
1
2
3
4
5
6
7
8
9
10
function push(array, ...items) {
array.push(...items);
}
function add(x, y) {
return x + y;
}
const numbers = [4, 38];
add(...numbers) // 42
扩展运算符与正常的函数参数可以结合使用,非常灵活:
1
2
3
function f(v, w, x, y, z) { }
const args = [0, 1];
f(-1, ...args, 2, ...[3]);
扩展运算符后面还可以放置表达式:
1
2
3
4
const arr = [
...(x > 0 ? ['a'] : []),
'b',
];
如果扩展运算符后面是一个空数组,则不产生任何效果:
1
2
[...[], 1]
// [1]
注意,只有函数调用时,扩展运算符才可以放在圆括号中,否则会报错:
1
2
3
4
5
6
7
8
(...[1, 2])
// Uncaught SyntaxError: Unexpected number
console.log((...[1, 2]))
// Uncaught SyntaxError: Unexpected number
console.log(...[1, 2])
// 1 2
替代函数的 apply() 方法
由于扩展运算符可以展开数组,所以不再需要 apply() 方法将数组转为函数的参数了
1
2
3
4
5
6
7
8
9
10
11
12
13
// ES5 的写法
function f(x, y, z) {
// ...
}
var args = [0, 1, 2];
f.apply(null, args);
// ES6 的写法
function f(x, y, z) {
// ...
}
let args = [0, 1, 2];
f(...args);
下面是扩展运算符取代 apply() 方法的一个实际的例子,应用 Math.max() 方法,简化求出一个数组最大元素的写法:
1
2
3
4
5
6
7
8
// ES5 的写法
Math.max.apply(null, [14, 3, 77])
// ES6 的写法
Math.max(...[14, 3, 77])
// 等同于
Math.max(14, 3, 77);
扩展运算符的应用
复制数组
ES5 只能用变通方法来复制数组:
1
2
3
4
5
const a1 = [1, 2];
const a2 = a1.concat();
a2[0] = 2;
a1 // [1, 2]
扩展运算符提供了复制数组的简便写法:
1
2
3
4
5
const a1 = [1, 2];
// 写法一
const a2 = [...a1];
// 写法二
const [...a2] = a1;
合并数组
扩展运算符提供了数组合并的新写法:
1
2
3
4
5
6
7
8
9
10
11
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' ]
不过,这两种方法都是浅拷贝,使用的时候需要注意。
与解构赋值结合
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// ES5
a = list[0], rest = list.slice(1)
// ES6
[a, ...rest] = list
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 // []
如果将扩展运算符用于数组赋值,只能放在参数的最后一位,否则会报错:
1
2
3
4
5
const [...butLast, last] = [1, 2, 3, 4, 5];
// 报错
const [first, ...middle, last] = [1, 2, 3, 4, 5];
// 报错
字符串
扩展运算符还可以将字符串转为真正的数组:
1
2
3
4
5
6
[...'hello']
// [ "h", "e", "l", "l", "o" ]
// 上面的写法,有一个重要的好处,那就是能够正确识别四个字节的 Unicode 字符
'x\uD83D\uDE80y'.length // 4
[...'x\uD83D\uDE80y'].length // 3
正确返回字符串长度的函数,可以像下面这样写:
1
2
3
4
5
function length(str) {
return [...str].length;
}
length('x\uD83D\uDE80y') // 3
实现了 Iterator 接口的对象
任何定义了遍历器(Iterator)接口的对象,都可以用扩展运算符转为真正的数组。
1
2
let nodeList = document.querySelectorAll('div');
let array = [...nodeList];
Map 和 Set 结构,Generator 函数
扩展运算符内部调用的是数据结构的 Iterator 接口,因此只要具有 Iterator 接口的对象,都可以使用扩展运算符,比如 Map 结构:
1
2
3
4
5
6
7
let map = new Map([
[1, 'one'],
[2, 'two'],
[3, 'three'],
]);
let arr = [...map.keys()]; // [1, 2, 3]
Generator 函数运行后,返回一个遍历器对象,因此也可以使用扩展运算符
1
2
3
4
5
6
7
const go = function*(){
yield 1;
yield 2;
yield 3;
};
[...go()] // [1, 2, 3]
如果对没有 Iterator 接口的对象,使用扩展运算符,将会报错:
1
2
const obj = {a: 1, b: 2};
let arr = [...obj]; // TypeError: Cannot spread non-iterable object
Array.from()
Array.from()
方法用于将两类对象转为真正的数组:类似数组的对象(array-like object)和可遍历(iterable)的对象(包括 ES6 新增的数据结构 Set 和 Map)。
示例:将一个类似数组的对象,Array.from() 将它转为真正的数组
1
2
3
4
5
6
7
8
9
10
11
12
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']
常见的类似数组的对象是 DOM 操作返回的 NodeList 集合,以及函数内部的 arguments 对象。Array.from() 都可以将它们转为真正的数组:
1
2
3
4
5
6
7
8
9
10
11
// NodeList 对象
let ps = document.querySelectorAll('p');
Array.from(ps).filter(p => {
return p.textContent.length > 100;
});
// arguments 对象
function foo() {
var args = Array.from(arguments);
// ...
}
只要是部署了 Iterator 接口的数据结构,Array.from() 都能将其转为数组:
1
2
3
4
5
Array.from('hello')
// ['h', 'e', 'l', 'l', 'o']
let namesSet = new Set(['a', 'b'])
Array.from(namesSet) // ['a', 'b']
如果参数是一个真正的数组,Array.from() 会返回一个一模一样的新数组:
1
2
Array.from([1, 2, 3])
// [1, 2, 3]
扩展运算符(…
)也可以将某些数据结构转为数组:
1
2
3
4
5
6
7
// arguments对象
function foo() {
const args = [...arguments];
}
// NodeList对象
[...document.querySelectorAll('div')]
Array.of()
Array.of() 方法用于将一组值,转换为数组:
1
2
3
Array.of(3, 11, 8) // [3,11,8]
Array.of(3) // [3]
Array.of(3).length // 1