gpt4 book ai didi

javascript - Object.assign 查询

转载 作者:行者123 更新时间:2023-12-05 00:28:16 24 4
gpt4 key购买 nike

let user = { name: "Nasir", age: 25 };
let employee = Object.assign( {}, user, { add: "dhaka", age: 35 } );

console.log( user ); //{ name: 'Nasir', age: 25 }
console.log( employee ); // { name: 'Nasir', age: 35, add: 'dhaka' }

//------------------------------------------//

let user1 = { name: "ahmed" };
let employee1 = Object.assign( user1, { permission: "can edit" } );

console.log( user1 ); // { name: 'ahmed', permission: 'can edit' }
console.log( employee1 ); //{ name: 'ahmed', permission: 'can edit' }
为什么user1对象获取属性:permission ?
我复制了 user1对象属性到 employee1并添加其他属性 permission , 所以 permission应该找到
仅在 employee1 上对象,不在 user1 中.
请指导我,我错过了什么?

最佳答案

因为,Object.assign()有语法 Object.assign(target, source)所以你使用user1作为目标。因此,使用一个空对象 {}作为目标,以便将对象合并到该目标中,user1对象不变。

let user1 = {
name: "ahmed"
};
let employee1 = Object.assign({}, user1, {
permission: "can edit"
});
console.log(user1); // { name: 'ahmed' }
console.log(employee1); //{ name: 'ahmed', permission: 'can edit' }

您甚至可以使用扩展语法来实现这一点:

let user1 = {
name: "ahmed"
};
let employee1 = {
...user1,
...{ permission: "can edit" }
}
console.log(user1); // { name: 'ahmed' }
console.log(employee1); //{ name: 'ahmed', permission: 'can edit' }

关于javascript - Object.assign 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67069593/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com