javascript ko.utils.arrayFirst 在不处理带有非空字符串的 else 块时总是返回 null
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21222480/
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
ko.utils.arrayFirst always returns null when not handling else block with non-empty string
提问by formatc
This works correctly:
这正常工作:
self.getById = function(id) {
return ko.utils.arrayFirst(self.PostArray(), function(item) {
if (item.postId === id) {
return item;
}
else {
return 'not found';
}
});
};
console.log(self.PostArray().length);
console.log(self.getById(170));
But if I put return ''
or return null
in else block I always get null, why is that?
但是如果我把return ''
或return null
放在 else 块中,我总是得到空值,这是为什么呢?
回答by Andrew Whitaker
You're not using arrayFirst
correctly. arrayFirst
expects a function that returns true
or false
, evaluating each item. The first item for which the function returns true
is returned. Here's how it should look:
你没有arrayFirst
正确使用。arrayFirst
期望一个返回true
or的函数false
,评估每个项目。返回函数返回的第一项true
。这是它的外观:
self.getById = function(id) {
return ko.utils.arrayFirst(self.PostArray(), function(item) {
return item.postId === id;
}) || 'not found';
};
Basically return 'not found'
if item
is falsey (null
in this case most likely).
基本上返回'not found'
如果item
是假的(null
在这种情况下最有可能)。
See this articlefor more information on the various utility functions in KnockoutJS.
有关KnockoutJS 中各种实用程序函数的更多信息,请参阅本文。