这可以正确工作:
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));
但如果我把return ''
or return null
在 else 块中我总是得到 null,为什么呢?
你没有使用arrayFirst
正确。arrayFirst
期望有一个返回的函数true
or false
,评估每个项目。函数返回的第一项true
被返回。它应该是这样的:
self.getById = function(id) {
return ko.utils.arrayFirst(self.PostArray(), function(item) {
return item.postId === id;
}) || 'not found';
};
基本回归'not found'
if item
是假的(null
在这种情况下最有可能)。
See 本文 http://www.knockmeout.net/2011/04/utility-functions-in-knockoutjs.html有关 KnockoutJS 中各种实用函数的更多信息。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)