Javascript 如何将while循环计数器设置为从1开始,而不是从0开始
这是我的密码:Javascript 如何将while循环计数器设置为从1开始,而不是从0开始,javascript,javascript-events,Javascript,Javascript Events,这是我的密码: 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 = docum
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++;
}
}
函数列表甜点(){
var甜点列表=[“布丁”、“蛋糕”、“太妃糖”、“冰淇淋”、“软糖”、“坚果糖”];
var i=0;
while(i
由于我根据数组中的数字项设置li标记ID,因此我将其设置为零。相反,我想修改I,以便它设置以1开头的ID,而不跳过第一个数组成员。我试过一些方法,但是我错过了这个。有人吗?使用
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++;
}
var i=1;
而(i var nliID='item-'+(i-1);//在迭代数组时,计数器变量应始终从0
运行到length-1
。其他解决方案是可能的,但与直觉相反
如果您在该数组中有一些基于一的数字,只需在需要的地方使用i+1
;在您的情况下使用'item-'+(i+1)
顺便说一句,你可能只是在循环体中使用a而不是,而可能只是在循环体中使用i+1而不是i
?@uhehehesh这应该是答案。=]
可能for
在这种情况下更好?应该是甜点列表。长度+1
?@codingbiz:你的解决方案跳过数组的成员。我已经尝试过了问题:你说的“基于一的数字”是什么意思?此外,我想到了for循环,但后来认为while循环更合适。如何确定使用这两种结构的最佳时间?与-wow相反,Wikipedia确实有一篇关于该术语的文章:-):对于数组迭代,使用已知的重复次数和其他通常用于循环的简单条件,它们增加了可读性。我想这是我个人的偏好,我很少使用while循环——只有当所有循环语句都不适合一行时才使用。