我的对象散布运算符用法有什么问题?

时间:2018-12-14 19:48:09

标签: javascript ecmascript-6 operator-keyword ecmascript-7 spread-syntax

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,我在做什么错了?

4 个答案:

答案 0 :(得分:2)

您正在将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));

答案 1 :(得分:1)

首先,您不是在改变原始的color3对象,而是返回一个新的对象。其次:

({ ...colorName, Nrating });

将返回带有第四个道具Nrating: 6的新对象,因为它是对象分配的简写。您只需要简单地将值分配给rating键即可。

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

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

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

答案 2 :(得分:0)

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

答案 3 :(得分:0)

您已经创建了一个新属性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