...运算符的名称是什么?

时间:2017-06-27 17:33:21

标签: javascript

...运算符是"传播"具有两种不同语义的运算符,具体取决于其词法位置(参数位置与解构赋值,数组,参数位置等)?

或者它有两个名字" spread"和"休息"?

2 个答案:

答案 0 :(得分:3)

根据使用情况,它是同一个具有不同名称的运算符。

休息属性

Rest属性收集剩余的自身可枚举属性键,这些键尚未被解构模式拾取。这些键及其值将复制到新对象上。

let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };
x; // 1
y; // 2
z; // { a: 3, b: 4 }

传播资源

对象初始值设定项中的Spread属性将自己的可枚举属性从提供的对象复制到新创建的对象上。

let n = { x, y, ...z };
n; // { x: 1, y: 2, a: 3, b: 4 }

more ...

答案 1 :(得分:0)

它们非常不同,因为Spread Operator将收集的元素(例如数组)解包为单个元素。但是Rest Operator将所有剩余的元素收集到一个数组或对象中。例如; 散布在阵​​列上:

const arrOne = ['I', 'love', 'Programming']
const arrTwo = ['Programming', 'is', 'life']

const arrThree = [...arrOne, 'and', ...arrTwo]
console.log(arrThree);

输出为:['I','love','Programming','Programming','is','life']

放置在数组上: 通过破坏数组,

const [idx1, ...restArrValue] = arrOne;
console.log(idx1, restArrValue);

输出为:I ['love','Programming']

再次打开包装即可传播

console.log(idx1, ...restArrValue);

输出为:我喜欢编程

我认为这个概念也很清楚。