【发布时间】:2020-12-05 23:11:42
【问题描述】:
(除了 foreach、map、reduce、filter、for、while 和 do while) (返回 true(如果没有找到具有属性 read 的对象:false)或 false(如果任何一个对象包含属性 read:false)。) 考虑以下数组:
let allRead = true;
let notifications = [
{message: ‘Lorem’, read: true},
{message: ‘Ipsum’, read: true},
{message: ‘Dolor’, read: true},
{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);
另一方面,使用 some 已经部分成功......但是它在 read 时返回 true:找到 false 但我想要的是如果 read: false found 然后将 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);
【问题讨论】:
-
您正在寻找
some或every。 -
我的回答有帮助吗?
标签: javascript arrays loops dictionary iterator