【问题标题】:Is there any Higher order function which can iterate through a array of objects and return true or false是否有任何高阶函数可以遍历对象数组并返回真或假
【发布时间】: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);

【问题讨论】:

  • 您正在寻找someevery
  • 我的回答有帮助吗?

标签: javascript arrays loops dictionary iterator


【解决方案1】:

您可以使用Array#every 检查数组中的所有元素是否符合给定条件。

const allRead = notifications.every(({read})=>read);

您也可以使用Array#some,通过简单地否定结果来检查是否没有符合条件的元素。

const allRead = !notifications.some(({read})=>!read);

【讨论】:

    【解决方案2】:

    如果要检查数组列表中的所有值(在本例中为对象数组),如果不为假,则需要通过一定的条件才能返回真,可以使用 array.every。 需要更多信息或示例,如果这不是您要查找的内容..

    参考 MDN:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-27
      • 2021-11-05
      • 2019-07-01
      • 2016-08-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多