2017-07-25 98 views
0

作为练习,我想编写一个类似于Array.prototype.every()方法的函数all()。只有提供的谓词对数组中的所有项返回true时,此函数才返回true。如何在Javascript中编写Array.prototype.every()方法

Array.prototype.all = function (p) { 
    this.forEach(function (elem) { 
    if (!p(elem)) 
     return false; 
    }); 
    return true; 
}; 

function isGreaterThanZero (num) { 
    return num > 0; 
} 

console.log([-1, 0, 2].all(isGreaterThanZero)); // should return false because -1 and 0 are not greater than 0 

不知何故,这不起作用,并返回true。我的代码有什么问题?有没有更好的方法来写这个?

+0

[什么是\'返回\'关键字的可能的复制\'的forEach \'函数里面是什么意思? ](https://stackoverflow.com/questions/34653612/what-does-return-keyword-mean-inside-foreach-function) – juvian

+1

你可能会发现这个链接有趣http://reactivex.io/learnrx/并采取看看像lodash这样的图书馆https://lodash.com/docs/4.17.4 – JGFMK

+0

如果你看看你的控制台,你会发现你没有得到-1,0为真,2为真。没有杀死循环时它返回false。你不能用forEach杀死循环,因为它专门用于运行每个项目。 – Meggg

回答

0

您只能通过抛出异常停止forEach()循环。只需使用正常的for循环即可。

Array.prototype.all = function (p) { 
    for(var i = 0; i < this.length; i++) { 
    if(!p(this[i])) { 
     return false; 
    } 
    } 
    return true; 
}; 

如果不是Array.prototype.every()其他任何方法允许被使用,那么您可以:

Array.prototype.all = function (p) { 
    return this.filter(p).length == this.length; 
}; 
2

您不能通过返回来跳出Array#forEach循环。改用for循环。

注意:这是部分实施Array#every来演示返回问题。

Array.prototype.all = function (p) { 
 
    for(var i = 0; i < this.length; i++) { 
 
    if(!p(this[i])) { 
 
     return false; 
 
    } 
 
    } 
 
    
 
    return true; 
 
}; 
 

 
function isGreaterThanZero (num) { 
 
    return num > 0; 
 
} 
 

 
console.log([-1, 0, 2].all(isGreaterThanZero));

0

在返回的foreach功能不会从您的函数返回值。你可以这样编码。

 Array.prototype.all = function (p) { 
      for(var i = 0; i < this.length; i++){ 
       if (!p(this[i])) 
        return false; 
      }     
      return true; 
     }; 

     function isGreaterThanZero (num) { 
      return num > 0; 
     } 

     var result = [2, 3, 4].all(isGreaterThanZero); 
     console.log("result", result); 
0

其他答案有些不对。您传递的回调应该用3个参数调用:当前项目,索引和整个数组。这就是原生Array.every以及大多数本地数组函数的工作原理。你的回调可以选择使用这些参数,但大部分时间没有。

Array.prototype.all = function (p) { 
 
    for(var i = 0; i < this.length; i++) { 
 
    if (!p(this[i], i, this)) { 
 
     return false; 
 
    } 
 
    } 
 

 
    return true; 
 
}; 
 

 
function isGreaterThanZero (num) { 
 
    return num > 0; 
 
} 
 

 
console.log([-1, 0, 2].all(isGreaterThanZero)); // should return false because -1 and 0 are not greater than 0

+1

如果你打算使用完整的Array#每个实现,不要忘记添加['thisArg'](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array /每)。 –