我的对象传播运算符使用有什么问题?

What is wrong with my object spread operator usage?

var color3 = {
    name: 'Black',
    type: 'special',
    rating: 1
};

var rateColor3 = (colorName, Nrating) => ({ ...colorName, Nrating });
console.log(color3.rating); ///// 1
console.log(rateColor3(color3, 6).rating);//////1
console.log(color3.rating);//////1

我想在保持 color3 不可变的同时使用对象展开运算符, 但是我的第二个 console.log 的输出是 1 而不是 6,我做错了什么?

您正在将值 6 分配给对象的键 NRating,而不是现有的 rating

所以你的对象看起来像这样:

{
    name: 'Black',
    type: 'special',
    rating: 1,
    Nrating: 6
}

要覆盖现有的 rating 属性,您必须执行以下操作:

var rateColor3 = (colorName, Nrating) => ({ ...colorName, rating: Nrating });

或将参数 Nrating 更改为 rating

var color3 = {
    name: 'Black',
    type: 'special',
    rating: 1
};

var rateColor3 = (colorName, rating) => ({ ...colorName, rating });

console.log(rateColor3(color3, 6));

首先,您不是在改变原始 color3 对象,而是 return 创建一个新对象。其次:

({ ...colorName, Nrating });

将 return 一个带有第四个属性 Nrating: 6 的新对象,因为它是用于对象分配的 shorthand。您只需将值分配给 rating 键即可。

var color3 = {
    name: 'Black',
    type: 'special',
    rating: 1
};

var rateColor3 = (colorName, Nrating) => ({ ...colorName, rating: Nrating });

console.log(rateColor3(color3, 6));

Nrating 需要一个 属性 名称

var color3 = {
   name: 'Black',
   type: 'special',
   rating: 1
};

var rateColor3 = (colorName, Nrating) => ({ ...colorName, rating: Nrating });
console.log(color3.rating); ///// 1
console.log(rateColor3(color3, 6).rating);//////6
console.log(color3.rating);//////1

您创建了一个新的 属性 Nrating。将 rating 更改为 Nrating

var color3 = {
    name: 'Black',
    type: 'special',
    rating: 1
};

var rateColor3 = (colorName, Nrating) => ({ ...colorName, Nrating });
console.log(color3.rating); ///// 1
console.log(rateColor3(color3, 6).Nrating);//////6
console.log(color3.rating);//////1