javascript 如何使用eval为动态变量赋值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12268026/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 15:45:48  来源:igfitidea点击:

How to assign a value to a dynamic variable using eval?

javascript

提问by juria_roberts

I got the dynamic variable name doing

我得到了动态变量名

varname = "data" + newid + "['" + name + "']";

I would like to assign a value to the dynamic variable. I tried this

我想为动态变量赋值。我试过这个

eval(varname) = value; 

but it doesn't work. What do I need to do in order to assign a value to the dynamic variable?

但它不起作用。我需要做什么才能为动态变量赋值?

采纳答案by Jo?o Silva

var data1 = { a: 200 };
var newid = 1;
var name = "a";

var varname = "data"+newid+"['"+name+"']";
var value = 3;
eval(varname + "=" + value); // change data1['a'] from 200 to 3

Having said that, evalis evil. Are you really sure you need to use dynamic variables?

话虽如此,eval是邪恶的。你真的确定你需要使用动态变量吗?

回答by Quentin

Don't use eval. Don't use dynamic variables.

不要使用评估。不要使用动态变量。

If you have an unordered group of related data, store it in an object.

如果您有一组无序的相关数据,请将其存储在一个对象中。

var myData = {};
myData[ newid + name ] = value;

although it looks like you are dealing with a dynamic object so

虽然看起来你正在处理一个动态对象,所以

myData[ newid ] = myData[ newid ] || {};
myData[ newid ][ name ] = value;