我有多个变量,比如"s11“和"s12”等等。
var s11 = 0;
var s12 = 0;除此之外,我还有一个包含所有这些变量名称的数组。
var wA = new Array("s11", "s12");数组中的值稍后会根据用户活动自动添加到脚本中。
我的问题是,例如,我希望变量"s11“在每次作为数组中的值出现时都被设为++。这可以做到吗?
发布于 2013-07-01 00:52:16
使用变量,会让你的生活变得艰难。这里有一种方法可以同时做到这两点。使用关联数组,如下所示:
var count = {};
var wA = new Array("s11", "s12");
function updateArray(value) {
wA.push(value);
if(! (value in count) ) {
count[value] = 0;
}
count[value]++;
}然后像这样使用它:
updateArray("s11");
updateArray("s12");现在count看起来像:{s11: 1, s12: 1} & wA看起来像:['s11', 's12']
发布于 2013-07-01 00:52:27
您可以使用eval()函数。它运行任何作为参数给出的代码。例如,要在每个变量的名称出现在数组中时对其执行++操作,请使用:
for(variablename in wA){ // or any other way to loop through the array
eval(variablename + "++");
}另外,您可以像使用关联数组一样使用owner对象。如果变量是全局变量,只需使用window即可。
for(variablename in wA){ // or any other way to loop through the array
window[variablename]++;
}发布于 2013-07-01 00:52:30
如果你的s变量是全局的,那么你可以在下面加点:
for (var i = wA.length; i--;)
window[wA[i]] ++;https://stackoverflow.com/questions/17392633
复制相似问题