在Java脚本的增量循环中递增和重复3次

时间:2014-10-27 19:18:30

标签: javascript

所以我们的目标是拥有以下内容:

k_1_1
k_1_2
k_1_3

k_2_4
k_2_5
k_2_6

k_3_7
and so on

到目前为止我所拥有的是:

但我想我离开了......

while (var qi = 0; qi <= 9; qi++ ) {
  for(var ai = 0; ai <= 3; ai++ ) {
    var thisName = "k_" + ai + "_" + qi;
    var thisValue = "";
    localStorage.setItem(thisName, thisValue);
  }
}

任何帮助都会被贬低。

感谢

3 个答案:

答案 0 :(得分:1)

如果你使用一点点聪明才不需要两个循环:

for (var i = 0; i <= 9; i++) {

  var thisName = "k_" + (Math.floor(i/3)+1) + "_" + (i+1);

  var thisValue = "";
  localStorage.setItem(thisName, thisValue);
}

答案 1 :(得分:0)

您正在使用带有For循环参数的While循环。循环保持循环,而条件为TRUE。为什么不像这样切换到For循环(同样,你的qi和ai被切换):

for(var qi = 1; qi <= 9; qi++ ) {
 for(var ai = 1; ai <= 3; ai++ ) {
  var thisName = "k_" + qi + "_" + ai;
  var thisValue = "";
  localStorage.setItem(thisName, thisValue);
 }
}

答案 2 :(得分:0)

另一种解决方案:

for (var ai = 1; ai <= (27) ; ai++ ) { // 27 was picked arbitrarily (3 * 9)
                                       // set to what ever upper limit you need

    // the ceiling of the current ai number divided by 3 will give you your qi
    var qi = Math.ceil((ai/3));

    //setting your values
    var thisName = "k_" + qi + "_" + ai;
    var thisValue = "";

    //reporting
    console.log(thisName, thisValue);
}