作为练习,我想编写一个类似于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
。我的代码有什么问题?有没有更好的方法来写这个?
[什么是\'返回\'关键字的可能的复制\'的forEach \'函数里面是什么意思? ](https://stackoverflow.com/questions/34653612/what-does-return-keyword-mean-inside-foreach-function) – juvian
你可能会发现这个链接有趣http://reactivex.io/learnrx/并采取看看像lodash这样的图书馆https://lodash.com/docs/4.17.4 – JGFMK
如果你看看你的控制台,你会发现你没有得到-1,0为真,2为真。没有杀死循环时它返回false。你不能用forEach杀死循环,因为它专门用于运行每个项目。 – Meggg