动态Javascript变量名称 [英] Dynamic Javascript variable names
本文介绍了动态Javascript变量名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
javascript - 动态变量
我可以拥有这样的东西是Jquery
Can I have something like this is Jquery
for(var i=0;i<10;i++)
{
var (eval(i+17)) = y;
y++;
}
我需要这个因为我想在飞行中创建动态变量任何应该是能够将值赋值给它。
I need this because I want to have dynamic variable created on fly any should be able to asign values to it.
推荐答案
这里的正确答案是使用数组:
The correct answer here is to use arrays:
var arr = [];
for (var i = 0; i < 10; i++) {
arr[i + 17] = y;
y++;
}
如果你知道当前的上下文,你可以用同样的方式创建变量。比如说,对于全局(窗口
)范围:
If you know your current context, you can create variables in it the same way. Say, for the global (window
) scope:
for (var i = 0; i < 10; i++) {
window[i + 17] = y;
y++;
}
但这意味着你用随机变量名称在整个范围内踩踏。改为将它们保存在一个数组中。
But that means you're stomping all over your scope with random variable names. Keep them in one array instead.
这篇关于动态Javascript变量名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文