下划线 _.findWhere 数组中存在时找不到元素

Underscore _.findWhere not finding element in array when it exists

我正在尝试使用 Underscore.js 库的 findWhere 函数从 node.js 服务器上的数组中有效地查找对象,但我不明白为什么它总是 return未定义。

我使用节点控制台测试了该功能,对象明确包含一个具有指定键的对象,但在使用 findWhere 时仍然没有 returned。

在这里,我确保我在 findWhere 中寻找的 'fixture' 键的值确实等于我希望拥有的对象中的匹配值 returned:

'55785f4e38bd12511018145d' == predictions[0].fixture;

true

在检查 findWhere 正在搜索的数组中包含哪些值时,我确认该值确实存在:

predictions

[ { fixture: '55785f4e38bd12511018145d' } ]

正在检查我希望得到的值 returned:

predictions[0].fixture

'55785f4e38bd12511018145d'

运行 return 未定义的 findWhere 查询:

var foundPrediction = underscore.findWhere(predictions, {fixture: '55785f4e38bd12511018145d'});

undefined

我能想到的唯一原因是这可能与转换有关,或者可能与函数中 returns false 的“===”有关,但我有什么办法可以得到根据需要在何处找到 return 对象,还是我必须使用 for 循环进行手动搜索?

提前致谢!

您的代码没有任何问题。看起来您在控制台中 运行,这就是为什么在按下 enter 后,控制台显示未定义。您可能认为 foundPrediction 值未定义。您需要控制 foundPrediction 变量以获得所需的结果。

此外,铸造也没有错,因为它 returns 正确。

var predictions = [{
    fixture:'55785f4e38bd12511018145d'
}]
console.log('55785f4e38bd12511018145d' === predictions[0].fixture);
var foundPrediction = _.findWhere(predictions, {fixture: '55785f4e38bd12511018145d'});
console.log(foundPrediction);

我已经在jsFiddle中添加了代码。希望对你有帮助