Skip to content Skip to sidebar Skip to footer

Javascript For Loop Vs For In Does Not Work

I wrote two functions named some and every to expect to get results shown as below: console.log(every([NaN, NaN, NaN], isNaN)); // → true console.log(every([NaN, NaN, 4], isNaN)

Solution 1:

for..in iterates through the property names of the object you are iterating over.

In this case, those would be 0, 1, 2, so your attempt is calling the predicate on those and not the actual array elements.

Don't use for..in with arrays. The order of iteration is not guaranteed and it can wind up iterating over non-index properties.

Solution 2:

If you don't want to use a traditional for loop, consider using a for…of loop, which iterates through the elements in an array. for…in iterates through the keys.

functionevery (array, predicate) {
    for (var element of array) {
        if (!predicate(element)) {
            returnfalse;
        }
    }
    returntrue;
}

docs for for…of

Note: per the documentation, this requires an implementation that runs the ES6 Harmony proposal.

Post a Comment for "Javascript For Loop Vs For In Does Not Work"