本文介绍了JavaScript for循环vs for in不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
console.log(every( [NaN,NaN,NaN] isNaN));
//→true
$ b $ console.log(every([NaN,NaN,4],isNaN));
//→false
console.log(some([NaN,3,4],isNaN));
//→true
console.log(some([2,3,4],isNaN));
//→false
我的功能是:
函数every(array,predicate){
for(var element in array){
if(!predicate(element))
返回false;
}
返回true; (元素){
}
函数some(array,predicate){
for(var array in array){
if(predicate(element))
return true ;
}
返回false;
但是结果都是 false
一旦我将替换为
中的
$ b
函数every(array,predicate){
for($如果(!谓词(数组[i]))
返回false; var i = 0; i< array.length; i ++)
}
返回true;
函数some(array,predicate){
for(var i = 0; i< array.length; i ++){
if(predicate数组[i]))
返回true;
}
返回false;
$ / code>
为什么
for..in 来解决这个问题。
> for
循环,可以考虑使用来循环
循环,循环遍历数组中的元素。 for ... in
遍历键。
pre $函数every(array,谓词){
(数组元素){
if(!predicate(element)){
return false;
}
}
返回true;
}
的rel =nofollow> docs的-US / docs / Web / JavaScript / Reference / Statements / for ... >
注意:根据文档,这需要运行ES6 Harmony提议的实现。
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?
解决方案 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.
function every (array, predicate) {
for (var element of array) {
if (!predicate(element)) {
return false;
}
}
return true;
}
Note: per the documentation, this requires an implementation that runs the ES6 Harmony proposal.
这篇关于JavaScript for循环vs for in不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!