這個問題在這里已經有了答案: Object.assign() - 奇怪的行為需要解釋 2 個答案 3 小時前關閉。
我正在嘗試宣告一個名為newRobot
. newRobot
應該是一個新物件,它具有robot
以下物件的所有屬性和屬性:{laserBlaster: true, voiceRecognition: true}
. 應該在 的幫助下完成Object.asign()
。我不想改變robot
物件。
這是關于最后一條評論之后的代碼。這是到目前為止的代碼:
const robot = {
model: 'SAL-1000',
mobile: true,
sentient: false,
armor: 'Steel-plated',
energyLevel: 75
};
// What is missing in the following method call?
const robotKeys = Object.keys(robot);
console.log(robotKeys);
// Declare robotEntries below this line:
const robotEntries = Object.entries(robot);
console.log(robotEntries);
// Declare newRobot below this line:
const newRobot = Object.assign(robot, {laserBlaster: true, voiceRecognition: true})
console.log(newRobot);
uj5u.com熱心網友回復:
傳遞給的第一個引數Object.assign
是要修改的具體物件實體。
因此,要創建一個新物件,您需要將一個空物件 {}
作為Object.assign
.
const
newRobot = Object.assign({}, robot, { laserBlaster: true, voice: true });
// ^^
uj5u.com熱心網友回復:
如果您想在Object.assign
不更改第一個物件的情況下使用,您可以這樣做
Object.assign
從右到左合并所有屬性更改第一個物件
const robot = {
model: 'SAL-1000',
mobile: true,
sentient: false,
armor: 'Steel-plated',
energyLevel: 75
};
const newProperties = {laserBlaster: true, voiceRecognition: true}
// Declare newRobot below this line:
const newRobot = Object.assign({},robot, newProperties)
//or
const otherRobot = {...robot, ...newProperties}
console.log({robot, newRobot, otherRobot});
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/474753.html
標籤:javascript
上一篇:連接多個具有相同名稱和索引的物件
下一篇:返回列表