如何解决是否有任何高阶函数可以遍历对象数组并返回true或false
(foreach,map,reduce,filter,for,while和dowhile除外) (返回true(如果未找到属性读取为:false的对象)或false(如果任何一个对象包含属性读取为:false)。) 考虑以下数组:
let allRead = true;
let notifications = [
{message: ‘Lorem’,read: true},{message: ‘Ipsum’,{message: ‘Dolor’,{message: ‘Sit’,read: false},{message: ‘Amet’,read: true}
];
您必须使用内置的高阶函数将allRead变量设置为false。 通知数组。条件:a)您不能使用for,while,do-while循环b)您不能使用 forEach(),map(),reduce(),filter()。
到目前为止,我已经使用过一些并找到了。我很确定它找不到,因为find总是返回整个对象。除了迭代之外,您不能返回其他东西。
allRead = notifications.find((obj) => {
console.log("yes");
if (obj.read === false) {
console.log(obj.read);
return obj;
}
});
console.log(allRead);
另一方面,使用某些方法已部分成功...但是在读取时返回true:发现错误,但我想要的是如果读取:发现了false则将allRead设置为false,而不考虑其他迭代。
allRead = notifications.some((not) => not.read !== true);
console.log(allRead);
我还注意到,如果我使用if else条件或switch case语句并根据条件返回true,false,那么当它返回true时,它将自动中断并避免其他迭代。
allRead = notifications.some((not) => {
switch (not.read) {
case false:
break;
return false;
default:
return true;
}
});
console.log(allRead);
解决方法
您可以使用Array#every
来检查数组中的所有元素是否都符合给定条件。
const allRead = notifications.every(({read})=>read);
您也可以使用Array#some
,只需对结果求反即可检查是否没有符合条件的元素。
const allRead = !notifications.some(({read})=>!read);
,
如果要检查数组列表中的所有值(在这种情况下为对象数组)需要通过某些条件以返回true(如果不是false),则可以使用array.every。 需要更多信息或示例,如果这不是您想要的。
参考MDN:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。