使用For循环Javascript动态创建变量

时间:2011-08-23 13:16:12

标签: javascript variables for-loop

标题加上以下示例对我未实现的内容不言自明:-) 我们的想法是更换一些东西+计数器,以使其有效。

      for (var counter = 1; counter <= 6; counter++) {
        var something + counter = $('element' + counter);
        (something + counter).removeAttribute('class');
      }     

5 个答案:

答案 0 :(得分:3)

您可以创建一个数组,但更简单:

  for (var counter = 1; counter <= 6; counter++) {
    $('element' + counter).removeAttribute('class');
  } 

答案 1 :(得分:3)

只是做:

for (var counter = 1; counter <= 6; counter++) {
    $('element' + counter).removeAttribute('class');
}

除非您想将其存储在循环之外,否则请使用数组。

答案 2 :(得分:2)

使用数组。

var something = [];
for (var counter = 1; counter <= 6; counter++) {
    something[counter] = $('element' + counter);
    something[counter].removeAttribute('class');
}

答案 3 :(得分:2)

为什么你不能完全摆脱var?

for (var counter = 1; counter <= 6; counter++) {
    $('element' + counter).removeAttribute('class');
}

答案 4 :(得分:0)

  for (var counter = 1; counter <= 6; counter++) {
    window[something + counter] = $('element' + counter);
    window[something + counter].removeAttribute('class');
  } 

之后,窗口对象中会有一组字段,名为something1,something2等(当然,如果something == "something"