Search code examples
javascriptarraysfor-in-loop

Adding functions to javascript's Array class breaks for loops


I was looking for a way to add max/min functions to JavaScript's Array class, which seemed to be a solved problem: JavaScript: min & max Array values?. However, when I tried using that, I started getting errors from my code. It turns out that this approach doesn't work with loops.

for(i in myArray) { console.log(i) } 

prints out


1
2
3
max
min

Is there another approach I can use?


Solution

  • The for...in loop is used for looping through properties of an object. If you want to get the values from your array, you can do this:

    for (var i = 0; i < myArray.length; i++)
    {
        console.log(myArray[i])
    }