在ES6中經(jīng)常看到 ... 這個(gè)操作符,經(jīng)常會(huì)讓人看的頭大,比如這樣的代碼
return {
...this.props,
...childMethods.reduce((acc, method) => ({
...acc,
[method]: this[method]
}), {})
};
rest參數(shù)
當(dāng)我們不確定函數(shù)參數(shù)的時(shí)候經(jīng)常使用arguments對(duì)象,ES6引入rest參數(shù)概念可以不再使用該對(duì)象
function add(...args) {
return args.reduce(((result, value) => result + value), 0);
}
add(1, 2, 3); // 6
rest參數(shù)也可以用于對(duì)象賦值
let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 }
x // 1
y // 2
z // { a: 3, b: 4 }
有兩個(gè)需要注意的地方
- rest參數(shù)后面不能再有其它參數(shù)
- rest參數(shù)不記入函數(shù)的
length屬性
拓展運(yùn)算符
拓展運(yùn)算符也是...,是rest參數(shù)的逆運(yùn)算,將一個(gè)數(shù)組轉(zhuǎn)為逗號(hào)分隔的參數(shù)序列,運(yùn)算符主要用于函數(shù)調(diào)用
console.log(...[1, 2, 3]);
console.log(1, 2, 3);
這兩句一樣一樣的,與解構(gòu)賦值結(jié)合
[first, ...rest] = [1, 2, 3]; // 效果同下
first = [1, 2, 3][0], rest = [1, 2, 3].slice(1);
[...'hello'] // [ "h", "e", "l", "l", "o" ]
在對(duì)象中也經(jīng)常使用
var props = {
a:1,
b:2,
c:3
};
var obj = {
...props,
d: 4,
e: 5
}
等同于
var props = {
a: 1,
b: 2,
c: 3
};
var obj = Object.assign({}, props, {
d: 4,
e: 5
})