Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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));
// → false

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

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

My functions are:

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 the results are all false

Once I change the for...in to for loop, 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 not result in the correct answer?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
119 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...