admin管理员组文章数量:1425886
Here's my code:
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++;
}
}
Since I'm setting the li tags IDs based on the number items in my array, i
sets it to zero as it should. Rather I want to modify i
so that it sets the IDs beginning with 1 without it skipping the first array member. I've tried a few things but I'm missing this. Anybody?
Here's my code:
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++;
}
}
Since I'm setting the li tags IDs based on the number items in my array, i
sets it to zero as it should. Rather I want to modify i
so that it sets the IDs beginning with 1 without it skipping the first array member. I've tried a few things but I'm missing this. Anybody?
-
3
Maybe just using
i+1
instead ofi
in the loop body? – Uhehesh Commented Dec 9, 2012 at 23:30 -
@Uhehesh That should be answer.
=]
– Fabrício Matté Commented Dec 9, 2012 at 23:33
2 Answers
Reset to default 3As you are iterating an array, the counter variable should always run from 0
to length-1
. Other solutions were possible, but are counter-intuitive.
If you have some one-based numberings in that array, just use i+1
where you need it; in your case 'item-'+(i+1)
.
Btw, you might just use a for
-loop instead of while
.
Use var i = 1
;
and use i-1
where you currently have i
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++;
}
本文标签: javascriptHow to set while loop counter to start at 1not 0Stack Overflow
版权声明:本文标题:javascript - How to set while loop counter to start at 1, not 0 - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745448583a2658777.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论