...
运算符,是 ES6 里一个新引入的运算法,也叫 展开/收集 运算符。可以展开一个可迭代对象重的所有项。
可迭代的对象一般是指可以被循环的,包括:string
, array
, set
等等。
基础用法 1: 展开
const a = [2, 3, 4]
const b = [1, ...a, 5]
b; // [1, 2, 3, 4, 5]
基础用法 2: 收集
function foo(a, b, ...c) {
console.log(a, b, c)
}
foo(1, 2, 3, 4, 5); // 1, 2, [3, 4, 5]
意思是如果没有命名参数的话,...
就会收集所有的参数,
function foo(...args) {
console.log(args)
}
foo(1, 2, 3, 4, 5); // [1, 2, 3, 4, 5]
这个运算符一定是在最后一个参数的位置,也很好理解,就是“收集前面剩下的参数”。
基础用法 3: 把 类数组 转换为 数组
类数组和数组非常接近,都可以拥有一系列元素,也有length 属性,最大的不同是:
类数组不具备数组的一系列方法。
类数组如何转换数组?
// ES5 时代
function bar() {
var args = Array.prototype.slice.call(arguments);
// 调用push 加几个元素
args.push(1, 2, 3);
}
bar(0)//args [0,1,2,3]
// ES6 时代
const args = [...arguments];
function bar() {
var args = Array.prototype.slice.call(arguments);
// 调用push 加几个元素
args.push(1, 2, 3);
foo.apply(null,args)
}
function foo(...args) { // 搜集参数到 args
args.push(4, 5, 6)
console.log(...args) // 展开args
}
bar(0); // 0 1 2 3 4 5 6
基础用法 4: 增加元素或属性
1: 为数组新增成员
const pokemon = ['KK', 'Peter'];
const charmander = '郑伊健';
const pokedex = [...pokemon, charmander];
console.log(pokedex);
//Result: [ 'KK', 'Peter', '郑伊健' ]
2: 为对象新增属性
const basicSquirtle = { name: 'Squirtle', type: 'Water' };
const fullSquirtle = {
...basicSquirtle,
species: 'Tiny Turtle',
evolution: 'Wartortle'
};
console.log(fullSquirtle);
//Result: { name: 'Squirtle', type: 'Water', species: 'Tiny Turtle', evolution: 'Wartortle' }
基础用法 5: 合并数组/对象
合并数组:
const pokemon = ['Squirtle', 'Bulbasur', 'Charmander'];
const morePokemon = ['Totodile', 'Chikorita', 'Cyndaquil'];
const pokedex = [...pokemon, ...morePokemon];
console.log(pokedex);
//Result: [ 'Squirtle', 'Bulbasur', 'Charmander', 'Totodile', 'Chikorita', 'Cyndaquil' ]
// 对象数组也一样:
const pokemon = [
{ name: 'Squirtle', type: 'Water' },
{ name: 'Bulbasur', type: 'Plant' }
];
const morePokemon = [{ name: 'Charmander', type: 'Fire' }];
const pokedex = [...pokemon, ...morePokemon];
console.log(pokedex);
//Result: [ { name: 'Squirtle', type: 'Water' }, { name: 'Bulbasur', type: 'Plant' }, { name: 'Charmander', type: 'Fire' } ]
合并对象:
const baseSquirtle = {
name: 'Squirtle',
type: 'Water'
};
const squirtleDetails = {
species: 'Tiny Turtle Pokemon',
evolution: 'Wartortle'
};
const squirtle = { ...baseSquirtle, ...squirtleDetails };
console.log(squirtle);
//Result: { name: 'Squirtle', type: 'Water', species: 'Tiny Turtle Pokemon', evolution: 'Wartortle' }
网友评论