javascript - every() some() 和函数返回函数

标签 javascript

<分区>

我正在学习 NodeSchool 的 Functional Javascript 类(class)。 “Every Some”练习提供了一个“goodUsers”对象数组来比较另一个用户列表(也是一个对象数组)。

我希望有人可以帮助我想象解决方案中发生的事情:

function checkUsersValid(goodUsers) {
  return function allUsersValid(submittedUsers) {
    return submittedUsers.every(function(submittedUser) {
      return goodUsers.some(function(goodUser) {
        return goodUser.id === submittedUser.id;
      });
    });
  };
}

module.exports = checkUsersValid;

这些是提供的说明:

# Task

Return a function that takes a list of valid users, and returns a function that returns true if all of the supplied users exist in the original list of users.

You only need to check that the ids match.

## Example

    var goodUsers = [
      { id: 1 },
      { id: 2 },
      { id: 3 }
    ]

    // `checkUsersValid` is the function you'll define
    var testAllValid = checkUsersValid(goodUsers)

    testAllValid([
      { id: 2 },
      { id: 1 }
    ])
    // => true

    testAllValid([
      { id: 2 },
      { id: 4 },
      { id: 1 }
    ])
    // => false

## Arguments

  * goodUsers: a list of valid users

Use array#some and Array#every to check every user passed to your returned function exists in the array passed to the exported function.

最佳答案

checkUsersValid:函数返回范围内具有 goodUsers 的函数。

allUsersValid:如果所有提交的用户都包含在 goodUsers 中,则返回 true。 goodUsers 变量可通过运行 checkUsersValid 创建的原始闭包提供给函数。

submittedUsers.every :在每个元素上运行回调。如果每次回调调用都返回 true,则返回 true。

goodUsers.some :在每个元素上运行回调。如果至少有一次调用将返回 true,则将返回 true。

return goodUser.id === submittedUser.id : goodUser 在上次回调的范围内。父范围内的 submittedUser。

换句话说,返回的函数检查所有提交的用户是否包含在良好用户中。为此,每个 提交的用户都需要在好用户中至少被引用一次(some)。

关于javascript - every() some() 和函数返回函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39459081/

相关文章:

javascript - React 函数式组件 - 说它不是一个函数

JavaScript Function.prototype.toSource() 在 Chrome 中不起作用

javascript - 将对象序列化为 JSON 而不向原型(prototype)添加任何内容

javascript - 为什么这个正则表达式不排除连字符或括号?

javascript - 在服务器上渲染客户端图表

javascript - Django:日期格式管理和 unique_together -> "20/03/2020"值具有无效的日期格式。它必须采用 YYYY-MM-DD 格式。”]

javascript - 如何在 TinyMCE 中覆盖语言标签

javascript - 如何在服务器端监听客户端事件

javascript - 是否有一个插件可以在我的网页中显示 HTML 代码

javascript - AngularJS 加载并使用 javascript 检查语法