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