-3

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
max7
  • 800
  • 2
  • 16
  • 37

2 Answers2

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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • that did it, thanks very much. Questions: what do you mean by "one-based numberings"? Also, I thought of a for loop but then figured a while loop was more appropriate. How does one determine the best time to use either construct? – max7 Dec 09 '12 at 23:42
  • 1
    The opposite of [zero-based numberings](http://en.wikipedia.org/wiki/Zero-based_numbering) - wow, Wikipedia really has an article on that term :-) – Bergi Dec 09 '12 at 23:46
  • 1
    [for vs while](http://stackoverflow.com/questions/2950931/for-vs-while-in-c-programming): For array iteration, known number of repeats and other simple conditions usually for-loops are used, they increase readability. I guess it's personal preference, I hardly use while-loops - only when all loop statements don't fit in a one-liner. – Bergi Dec 09 '12 at 23:50
1

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++;
}
codingbiz
  • 26,179
  • 8
  • 59
  • 96