I'm trying to loop through an Array which then uses innerHTML to create a new
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With