在for循环内创建多个变量 [英] Create multiple variables inside for loop

查看:104
本文介绍了在for循环内创建多个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在循环内创建多个新变量.新变量的数量取决于另一个变量的长度(下面使用的变量列表").

I am trying to create multiple new variables inside a loop. The number of new variables depends on the lenght of another variable (variable "list" used below).

for(var i = 0; i < list.lenght; i++) 
{ 
var counter + i;   // create new variable (i.e. counter1, counter2,...)
}

我在StackOverflow上发现了很多非常类似的问题,而答案大多是使用数组(即

I found a lot of very simmilar questions on StackOverflow, and the answer is mostly using an array (i.e. How do I create dynamic variable names inside a loop?).

如果使用建议的解决方案,是否要创建变量数组?因此,在我的情况下,我将创建多个计数器,然后可以将值添加到该变量,即:

If I use the suggested solution, do I create an array of variables? So in my case I will create multiple counters and I can then add values to that variables, i.e.:

counter6++;

如果不是这种情况,我该如何解决这个问题?

If that is not the case how could I tackle the problem?

我很抱歉要求您解释一个旧的答案,但是由于声誉低下,我无法对此旧评论发表评论.

I apologize for asking you to explain an old answer, but I cannot comment in the old one because of low reputation.

推荐答案

您在这里有一些选择:

全局创建它们(不是最佳实践):

Create them global (not best practice ) :

for(var i = 0; i < list.lenght; i++){ 
  window['counter' + i] = 0;   // create counter1, counter2,...)
}

使用对象:

var scope = {};
for(var i = 0; i < list.lenght; i++){ 
  scope['counter' + i] = 0;   // create scope.counter1, scope.counter2,...)
}

使用带有 with 关键字的对象

var scope = {};
for(var i = 0; i < list.lenght; i++){ 
  scope['counter' + i] = 0;   // create scope.counter1, scope.counter2,...)
}
with(scope){
 // here you can acesess keys in the scope object like them variable on the function scope
 counter0++
}

使用普通的旧数组

var scope = new Array(list.length);

这篇关于在for循环内创建多个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆