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?

Share Improve this question edited Feb 19, 2023 at 9:56 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Dec 9, 2012 at 23:28 max7max7 7982 gold badges16 silver badges37 bronze badges 2
  • 3 Maybe just using i+1 instead of i 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
Add a ment  | 

2 Answers 2

Reset to default 3

As 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