[英]Javascript: How to dynamicly add a number to a variable name?
Say I have to following code: 说我必须遵循以下代码:
var numb = $(selector).length;
And now I want to dynamicly make variables based on this: 现在我想基于此动态地创建变量:
var temp+numb = ...
How would I be able to do this? 我怎么能这样做?
Edit: 编辑:
I know some of you will tell me to use an array. 我知道有些人会告诉我使用数组。 Normally I would agree but in my case the var is already an array and I rly see no other solution than creating dynamic names. 通常我会同意,但在我的情况下,var已经是一个数组,除了创建动态名称,我没有看到任何其他解决方案。
In global scope (not recommended): 在全球范围内(不推荐):
window["temp"+numb]='somevalue;
window.console && console.log(temp3);
In a scope you create - also works serverside where there is no window scope 在您创建的范围内 - 也可以在没有窗口范围的服务器端工作
var myScope={};
myScope["temp"+numb]="someValue";
window.console && console.log(myScope.temp3);
Variables in Javascript are bound to objects. Javascript中的变量绑定到对象。 Objects accept both .
物体接受两者.
and []
notation. 和[]
表示法。 So you could do: 所以你可以这样做:
var num = 3;
window["foo"+num] = "foobar";
console.log(foo3);
PS - Just because you can do that doesn't mean you should, though. PS - 只是因为你能做到这一点并不意味着你应该这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.