为什么 lodash 'some' 函数不能按预期工作?

Why wouldn't lodash 'some' function work as expected?

我正在尝试使用 lodash 2.4.1 来了解 数组中是否至少有一个元素以 true 作为其值

所以我决定使用 lodash someany 函数。

我的代码是这样的:

if ( _.some([lineup.reachesMaxForeignPlayers(), lineup.reachesBudgetLimit()], true) ) {
  response.send(400, "La inclusión de este jugador no satisface las reglas del juego");
}

never 进入 if 块内部,即使第一个条件实际上计算为真。

我得到了:

console.log(lineup.reachesMaxForeignPlayers());
console.log(lineup.reachesBudgetLimit());

if 块之前,我实际上可以看到第一个语句评估为 true

它可能失败了什么?

我使用 lodash 2.4.1,因为它包含 Sails js 依赖项。

你应该使用一个函数:

function isTrue(v) {
  return v === true;
}

if ( _.some([lineup.reachesMaxForeignPlayers(), lineup.reachesBudgetLimit()], isTrue) ) {
  response.send(400, "La inclusión de este jugador no satisface las reglas del juego"); 
}

Lodash 文档:https://lodash.com/docs#some

我相信你打算将 Boolean 作为谓词传递(第二个参数)

_.some 正在检查您提供给它的集合是否至少包含您提供给它的类型的对象的一个​​实例。观察:

> _.some([true, false], true)
false

> _.some([true, undefined], Boolean)
true

您可以像这样传递一个函数:

> _.some([true, false], function(value) { return value === true; })
true

> _.some([undefined, false], function(value) { return value === true; })
false

不过,我建议使用 if (lineup.reachesBudgetLimit() || lineup.reachesMaxForeignPlayers())

编辑:

实际上,只使用 _.some[docs] 没有谓词默认为标识:

_.some(bool_arr) 

应该可以。

console.log(_.some([true, true, false]));
console.log(_.some([false, false, false]));
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/3.9.3/lodash.min.js"></script>
 


除了建议将 Boolean 作为谓词传递的其他答案。您还可以使用:

_.some(bool_arr, _.identity)

_.identity[docs]

This method returns the first argument provided to it.

当您将非函数值传递给 some 时,lodash 将其视为 属性 名称并尝试查找包含非虚假 属性 的对象给的名字。在您的示例中,您传递了 true,因此它会尝试访问 item1[true]item2[true] 等。由于存在 none,因此结果为假。

解决方案是完全省略第二个参数,在这种情况下它默认为 identity,即元素本身。