I'm new to coding and I would like to write a function in javascript that does the exact same task as foreach() in php but I can't figure out how. I know there is an each() function in Jquery which is similar but I would like to see what it would look like so I can learn from it. Can anybody help me with this?
Asked
Active
Viewed 573 times
-3
-
you can use `for(var i in list) { console.log(list[i]); }` – أنيس بوهاشم Mar 11 '14 at 19:26
-
1https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach – Dom Mar 11 '14 at 19:27
2 Answers
1
simply said:
[1,2,3,4].forEach(function(i) { console.log(i); });
but as أنيس بوهاشم@ suggests, it's better to use:
for(var i in list) {
console.log(list[i]);
}
because you're avoiding the use of a function call.
But my best advice to you would be to start first by opening a book about Javascript, or some good web course.
0
Is very important if you are going to use in to check with hasOwnProperty if not you can get more values specially if you are using libraries like prototype. hasOwnProperty will check if the property is direct property of the object
for (var i in list) {
if (list.hasOwnProperty(i)){
console.log(i);
}
}

Jorge Enrique Reyes Salas
- 423
- 2
- 6