-3

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?

Thegree0ne
  • 175
  • 1
  • 2
  • 11

2 Answers2

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.

scniro
  • 16,844
  • 8
  • 62
  • 106
zmo
  • 24,463
  • 4
  • 54
  • 90
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);
        }
    }