gpt4 book ai didi

javascript - 使用可变对象属性 JS

转载 作者:行者123 更新时间:2023-12-01 02:25:49 25 4
gpt4 key购买 nike

我想知道是否有一种方法可以引用指向对象属性的变量指针。例如,在以下代码中:

function foo(){
this.x=0;
this.y=0;
this.bar=0;
}
var attr={x:"100",y:"42"};
var test=new foo();
for(var key in attr){
test.key=attr[key];
}
console.log(test.x);
console.log(text.y);

我希望这个程序输出 100 和 42,以表明 test.x 和 test.y 已使用上述方法设置,该方法可以设置对象的任意属性。这是可能吗?预先感谢您的帮助。

最佳答案

function foo() {
this.x = 0;
this.y = 0;
this.bar = 0;
}

var attr = {
x: 100,
y: 42
};

// Your code:
/*var test = new foo();
for(var key in attr) {
test.key=attr['key'];
}*/

// Using Object.assign()
var test = Object.assign({}, new foo(), attr);

console.log(test.x);
console.log(test.y);

关于javascript - 使用可变对象属性 JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48820332/

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