javascript linq.js 返回值(默认)FirstOrDefault
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24830744/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
linq.js return value of (default) FirstOrDefault
提问by RJB
Trying to check on the result of linq.js FirstOrDefault(), but checking for null or undefined isn't working. Having some trouble debugging it, but I can see that it is returning some sort of object.
试图检查 linq.js FirstOrDefault() 的结果,但检查 null 或 undefined 不起作用。在调试它时遇到了一些麻烦,但我可以看到它正在返回某种对象。
There isn't any documentation for this method online that I could find.
我在网上找不到任何有关此方法的文档。
I've tried:
我试过了:
var value = Enumerable.From(stuff).FirstOrDefault('x => x.Name == "Doesnt exist"')
if (value) {
alert("Should be not found, but still fires");
}
if (value != null)
alert("Should be not found, but still fires");
}
回答by Jeff Mercado
The signatures for the FirstOrDefault()
function is:
该FirstOrDefault()
函数的签名是:
// Overload:function(defaultValue)
// Overload:function(defaultValue,predicate)
The first parameter is always the default value to return if the collection is empty. The second parameter is the predicate to search for. Your use of the method is wrong, your query should be written as:
如果集合为空,则第一个参数始终是要返回的默认值。第二个参数是要搜索的谓词。你使用的方法是错误的,你的查询应该写成:
var value = Enumerable.From(stuff)
.FirstOrDefault(null, "$.Name === 'Doesnt exist'");
回答by RJB
We figured out the answer as I was typing this out. Since there is so little documentation, I'll share.
当我打字时,我们找到了答案。由于文档太少,我将分享。
You need to move the lambda into a Where clause before the FirstOrDefault().
您需要将 lambda 移动到 FirstOrDefault() 之前的 Where 子句中。
When
什么时候
var someArray = ["Foo", "Bar"];
var result = Enumerable.From(someArray).Where('x => x == "Doesnt exist"').FirstOrDefault();
Result is undefined (correct)
结果未定义(正确)
When
什么时候
var someArray = ["Foo", "Bar"];
var result = Enumerable.From(someArray).Where('x => x == "Bar"').FirstOrDefault();
Result is 'Bar' (correct)
结果是“酒吧”(正确)
When
什么时候
var someArray = ["Foo", "Bar"];
var result = Enumerable.From(someArray).FirstOrDefault('x => x == "Bar"');
Result is 'Foo' (incorrect)
结果是“Foo”(不正确)