Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop through Array only shows last value

I'm trying to loop through an Array which then uses innerHTML to create a new

  • element for every entry in the array. Somehow my code is only showing the last value from the array. I've been stuck on this for a few hours and can't seem to figure out what I'm doing wrong.
    window.onload = function() {
    
    // Read value from storage, or empty array
    var names = JSON.parse(localStorage.getItem('locname') || "[]");
    var i = 0;
    
        n = (names.length);
        for (i = 0; i <= (n-1); i++) {
            var list = names[i];
            var myList = document.getElementById("list");
            myList.innerHTML = "<li class='list-group-item' id='listItem'>"+ list + "</li>" + "<br />";
        }
    }
    

    I have a UL with the id 'list' in my HTML.

  • like image 332
    Bart S. Avatar asked Jun 13 '14 12:06

    Bart S.


    People also ask

    Why does javascript loop only use the last value?

    You have some sort of for/next loop that then calls some asynchronous function. When the function runs, what you see when the code runs is that the last value of the loop index is the value that gets used in the function for every instance that it gets called.

    How do you find the last number in a for loop?

    You can use a list: def LCM(minN,maxN): count = 1 results = [] for i in range(count,(maxN*count)+1): results. append(minN*count) count = count + 1 print(results[-1]) # print the last elements of the list. So, when You call LCM(5, 7), You will get 35.

    Can for in loops be used in arrays?

    A for loop can be used to access every element of an array. The array begins at zero, and the array property length is used to set the loop end.

    Does for loop check condition every time?

    Syntax. The for loop consists of three optional expressions, followed by a code block: initialization - This expression runs before the execution of the first loop, and is usually used to create a counter. condition - This expression is checked each time before the loop runs.


    1 Answers

    Change your for loop:

    for (i = 0; i <= (n-1); i++) {
        var list = names[i];
        var myList = document.getElementById("list");
        myList.innerHTML += "<li class='list-group-item' id='listItem'>"+ list + "</li>" + "<br />";
    }
    

    Use += instead of =. Other than that, your code looks fine.

    like image 128
    chris97ong Avatar answered Oct 15 '22 11:10

    chris97ong