Ian*_*Ian 4 javascript variables
我在Javascript中有一组全局计数器变量:
var counter_0 = 0;
var counter_1 = 0;
var counter_2 = 0;
Run Code Online (Sandbox Code Playgroud)
等等
然后我有一个Javascript函数接受一个映射到那些全局计数器的'索引'号.在这个函数中,我需要使用传递给函数的'index'值来读取和写入这些全局计数器.
我希望它如何工作的示例,但当然根本不起作用:
function process(index) {
// do some processing
// if 'index' == 0, then this would be incrementing the counter_0 global variable
++counter_+index;
if (counter_+index == 13)
{
// do other stuff
}
}
Run Code Online (Sandbox Code Playgroud)
我希望我想要完成的事情是清楚的.如果不是,我会尽力澄清.谢谢.
编辑澄清:
我不是试图增加计数器的名称,而是增加计数器包含的值.
Koo*_*Inc 21
对我来说看起来像一个阵列,或者我错过了什么?
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 */
}
}
Run Code Online (Sandbox Code Playgroud)
Ben*_*wee 10
function process(index) {
// do some processing
var counter;
eval('counter = ++counter_'+index);
if (counter == 13)
{
// do other stuff
}
}
Run Code Online (Sandbox Code Playgroud)
确保索引确实是一个整数,否则可能会发生混乱.
编辑:其他人已经指出,如果可以,你应该使用数组.但是如果你坚持使用命名的全局变量,那么上面的方法就可以了.
编辑:bobince指出您可以使用窗口对象按名称访问全局变量,因此值得对以下内容进行任何归功:
function process(index) {
// do some processing
var counter = ++window['counter_' + index];
if (counter == 13)
{
// do other stuff
}
}
Run Code Online (Sandbox Code Playgroud)
其他答案都说"不要用eval()",但不是为什么.以下是MDC的解释:
不要使用eval!
eval()是一个危险的函数,它使用调用者的特权执行它传递的代码.如果您使用可能受恶意方影响的字符串运行eval(),您最终可能会使用您的网页/扩展程序的权限在用户的计算机上运行恶意代码.
对于常见用例,有eval()的安全替代方案.
| 归档时间: |
|
| 查看次数: |
13226 次 |
| 最近记录: |