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

时间:2015-06-10 18:14:24

标签: javascript arrays node.js frameworks underscore.js

我正在尝试使用Underscore.js libarary的findWhere函数从node.js服务器上的数组中有效地查找对象,我无法理解为什么它总是返回undefined。

我使用节点控制台测试了该函数,并且对象definetely包含一个具有指定键的对象,但在使用findWhere时仍然没有返回任何内容。

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

  

'55785f4e38bd12511018145d'==预测[0] .fixture;

     

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

  

预测

     

[{fixture:'55785f4e38bd12511018145d'}]

检查我希望返回的值:

  

预测[0] .fixture

     

'55785f4e38bd12511018145d'

运行返回undefined的findWhere查询:

  

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

     

未定义

我能想到的唯一原因是这可能与某些事情有关,或者可能是在函数中返回false的'===',但是有什么办法可以让findWhere按需要返回对象,或者我是否必须使用for循环进行手动搜索?

提前致谢!

1 个答案:

答案 0 :(得分:1)

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

同样,当它返回true时,没有任何错误。

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

我在jsFiddle添加了代码。希望它有所帮助

相关问题