3 回答

TA贡献1995条经验 获得超2个赞
在我看来像是一个数组,还是我错过了什么?
var counters = [0,0,0];
function process(index) {
++counters[index];
/* or ++counters[index]+index, not sure what you want to do */
if (counters[index] === 13) {
/* do stuff */
}
}

TA贡献1803条经验 获得超6个赞
function process(index) {
// do some processing
var counter;
eval('counter = ++counter_'+index);
if (counter == 13)
{
// do other stuff
}
}
确保索引确实是整数,否则可能导致混乱。
编辑:其他人指出,如果可以的话,应该使用数组。但是,如果您坚持使用命名的全局变量,那么上述方法将起作用。
编辑:bobince指出,您可以使用窗口对象通过名称访问全局变量,因此值得一提的是:
function process(index) {
// do some processing
var counter = ++window['counter_' + index];
if (counter == 13)
{
// do other stuff
}
}
其他答案都说“不要使用eval()”,但不是为什么。这是MDC的解释:
不要使用eval!
eval()是一个危险的函数,它以调用者的特权执行它传递的代码。如果使用可能受到恶意方影响的字符串运行eval(),则最终可能会在网页/扩展名的许可下在用户计算机上运行恶意代码。
对于常见用例,有eval()的安全替代方法。
添加回答
举报