最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to create variables dynamiccally in JavaScript - Stack Overflow

programmeradmin3浏览0评论

I'm looking for a way to create variables dynamically in javascript

eg

I have a loop

for (i=0;i<15;i++){
}

now I need to create variables dynamically eg var "a"+i for eavh value in the loop. Is this possible and how?

I'm looking for a way to create variables dynamically in javascript

eg

I have a loop

for (i=0;i<15;i++){
}

now I need to create variables dynamically eg var "a"+i for eavh value in the loop. Is this possible and how?

Share Improve this question asked May 24, 2010 at 9:25 ElitmiarElitmiar 36.8k77 gold badges182 silver badges233 bronze badges 2
  • 2 Can you just use an array? var array = []; for (i=0;i<15;i++){array[i] = ...}? – Matthew Flaschen Commented May 24, 2010 at 9:28
  • Array is the most suitable candidate here. It is unwise to use a lot of such variables in Javascript. – Kangkan Commented May 24, 2010 at 9:33
Add a comment  | 

7 Answers 7

Reset to default 9

Since you are dealing with numeric, sequential variables — use an array.

var foo = [];
for (var i = 0; i < 15; i++) {
    foo[i] = something;
}

If we presume that you will need several variables related to each iteration ([foo1,bar1], [foo2, bar2]...) then there are two approaches

Use arrays

var foo = [], bar = [];
foo[1] = "foo"; 
bar[1] = "bar";

Use an object

var myVars = {};
myVars["foo" + 1] = "foo";
myVars["bar" + 1] = "bar";

That last one could also be written as

 myVars.bar1 = "bar";

Do not use eval as some has suggested.

To fulfill your exact requirement, I know only eval():

eval("varname"+i+" = 'Hello';");

on the other hand, you could consider using an array. Much cleaner: They don't clutter the global namespace, and you can order variables neatly in groups.

arrayname[i] = value;

It would be unwise to pollute your namespace with such a large number of variables. Use an array instead.

You can use the evil eval function for this purpose:

for (var i=0; i < 15; i++){
    eval( 'var a' + i + ' = "something"' );
}

window mostly represents the global object on browsers. You can use either that or scope it to your own objects.

var my = {};

for(var i = 0; i < 15; i++) {
    my["a" + i] = "value: " + i;
}

console.log(my.a4); // "value: 4"

I would consider using array instead of variables. Array has push method which adds a new element to array.

发布评论

评论列表(0)

  1. 暂无评论