0
How to run an action for every item in a list?
I have a list of items. For every item in the list, i want to run an html code. For example for item in list Make a list with the value of the item That means if there are 6 items in an array, the html to make a <li> will be executed 6 times, any way to make this?
5 Antworten
+ 3
This way if I understand the question right
window.onload=function(){
a=["spam","eggs"]
for(i in a){
if(i<a.length){
var b=document.createElement("li");
var c=document.querySelector("body");
c.appendChild(b);
b.innerHTML=a[i];
}
}
}
+ 2
Russ I also read about someone talking about it here but i haven't really looked into it ,thks for reminding ,
+ 2
Thanks,i was just looking at stack flow answers and got reminded why I used to get length in ouput when I used for i in ,as it iterates over the keys of an object
+ 1
Abhay Can you explain why you used "for (i in a)" and "if (i<a.length)", please? I read that using for ... in is not good for iterating over arrays.
My version (adopted from yours):
let a = ["spam", "eggs"];
for (i of a) {
var b=...
...
b.innerHTML=i
}
+ 1
Abhay This is where I read it: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in