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?