【问题标题】:how to set while loop counter to start at 1, not 0如何设置while循环计数器从1开始,而不是0
【发布时间】:2012-11-27 09:31:27
【问题描述】:

这是我的代码:

function listDesserts (){
    var dessertList = ["pudding", "cake", "toffee", "ice cream", "fudge", "nutella"];

    var i = 0;
    while (i< dessertList.length){
        var ul = document.getElementById("thelist");
        var nli = document.createElement("li");
        var nliID = 'item-' +i;
        nli.setAttribute('id', nliID);
        nli.setAttribute('class', 'listitem');
        nli.innerHTML = dessertList[i];
        ul.appendChild(nli);
        i++;
    }
}

由于我根据数组中的项目数设置 li 标签 ID,因此我应将其设置为零。相反,我想修改 i 以便它设置以 1 开头的 ID,而不会跳过第一个数组成员。我已经尝试了一些东西,但我错过了这个。有人吗?

【问题讨论】:

  • 也许只是在循环体中使用i+1 而不是i
  • @Uhehesh 这应该是答案。 =]

标签: javascript javascript-events


【解决方案1】:

在迭代数组时,计数器变量应始终从0 运行到length-1。其他解决方案是可能的,但违反直觉。

如果您在该数组中有一些从 1 开始的编号,只需在需要的地方使用 i+1;在你的情况下'item-'+(i+1)

顺便说一句,您可能只使用for-loop 而不是while

【讨论】:

  • 做到了,非常感谢。问题:“从一开始的编号”是什么意思?另外,我想到了一个 for 循环,但后来发现一个 while 循环更合适。如何确定使用任一结构的最佳时间?
  • zero-based numberings 的反义词 - 哇,维基百科真的有一篇关于这个词的文章 :-)
  • for vs while:对于数组迭代,已知重复次数和其他通常使用for循环的简单条件,它们增加了可读性。我想这是个人喜好,我几乎不使用 while 循环 - 只有当所有循环语句都不适合单行时。
【解决方案2】:

使用var i = 1

并在您当前拥有i 的地方使用i-1

var i = 1;
while (i< dessertList.length-1){
    var ul = document.getElementById("thelist");
    var nli = document.createElement("li");
    var nliID = 'item-' + (i-1);    //<----- here
    nli.setAttribute('id', nliID);
    nli.setAttribute('class', 'listitem');
    nli.innerHTML = dessertList[i-1];    //<----- and here
    ul.appendChild(nli);
    i++;
}

【讨论】:

  • 也许for 在这种情况下更好?
  • 应该是dessertList.length + 1
  • @codingbiz:您的解决方案会跳过数组的成员。我曾尝试过类似的事情,但结果相同。
猜你喜欢
  • 2020-04-03
  • 1970-01-01
  • 2012-08-31
  • 1970-01-01
  • 2023-01-09
  • 1970-01-01
  • 2023-03-22
  • 2023-03-30
  • 1970-01-01
相关资源
最近更新 更多