简体   繁体   English

使用可变对象属性JS

[英]Use Variable Object Properties JS

I was wondering if there is a way to refrence a variable pointer to a property of an object. 我想知道是否有一种方法可以将变量指针引用到对象的属性。 For example, in the following code: 例如,在以下代码中:

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);

I would like this program to output 100 and 42 to show that test.x and test.y have been set using the above method that can set any arbitrary property of an object. 我希望该程序输出100和42,以显示已使用上述方法设置了test.x和test.y,该方法可以设置对象的任意属性。 Is this at all possible? 这是可能吗? Thanks in advance for the help. 先谢谢您的帮助。

 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); 

Please check this: 请检查以下内容:

 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(test.y); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM