如何动态设置Javascript对象值? [英] How to set a Javascript object values dynamically?
本文介绍了如何动态设置Javascript对象值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
很难用文字来解释这个案例,让我举一个例子:
It's difficult to explain the case by words, let me give an example:
var myObj = {
'name': 'Umut',
'age' : 34
};
var prop = 'name';
var value = 'Onur';
myObj[name] = value; // This does not work
eval('myObj.' + name) = value; //Bad coding ;)
如何在JavaScript对象中设置具有变量值的变量属性?
How can I set a variable property with variable value in a JavaScript object?
推荐答案
myObj[prop] = value;
这应该有效。您混淆了变量的名称及其值。但是使用字符串索引对象来获取其属性在JavaScript中可以正常工作。
That should work. You mixed up the name of the variable and its value. But indexing an object with strings to get at its properties works fine in JavaScript.
这篇关于如何动态设置Javascript对象值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文