gpt4 book ai didi

javascript - 如何在 Javascript 中编写 Array.prototype.every() 方法

转载 作者:行者123 更新时间:2023-12-01 03:19:32 24 4
gpt4 key购买 nike

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

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。我的代码有什么问题吗?有更好的写法吗?

最佳答案

你无法突破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));

关于javascript - 如何在 Javascript 中编写 Array.prototype.every() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45310138/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com