Javascript vs for in loop doesn't work

I wrote two functions, named by some and each, to expect the results shown below:

console.log(every([NaN, NaN, NaN], isNaN));
// → true

console.log(every([NaN, NaN, 4], isNaN));
// → false

console.log(some([NaN, 3, 4], isNaN));
// → true

console.log(some([2, 3, 4], isNaN));
// → false

      

My functions:

function every(array,predicate){
  for (var element in array){
    if (!predicate(element))
      return false;
  }
  return true;
}

function some(array, predicate){
  for (var element in array){
    if (predicate(element))
      return true;
  }
  return false;
}

      

But all the results false

Once I changed the loop for...in

to for

, the answers are correct.

function every(array, predicate) {
  for (var i = 0; i < array.length; i++) {
    if (!predicate(array[i]))
      return false;
  }
  return true;
}

function some(array, predicate) {
  for (var i = 0; i < array.length; i++) {
    if (predicate(array[i]))
      return true;
  }
  return false;
}

      

Why for..in

can't it lead to the correct answer?

-1


source to share


2 answers


If you don't want to use a traditional loop for

, consider using a loop for…of

that iterates through the elements in an array. for…in

iterates through the keys.

function every (array, predicate) {
    for (var element of array) {
        if (!predicate(element)) {
            return false;
        }
    }
    return true;
}

      



docs for for…of

Note: The documentation requires an implementation that runs the ES6 Harmony proposal.

0


source


for..in

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

In this case, they will be 0

, 1

, 2

, so your attempt to cause the predicate for people and not for the actual elements of the array.



Don't use for..in

with arrays
. The iteration order is not guaranteed and may end up iterating over non-indexed properties.

+3


source







All Articles