gpt4 book ai didi

javascript - ko.utils.arrayFirst 在不处理非空字符串的 else block 时总是返回 null

转载 作者:数据小太阳 更新时间:2023-10-29 04:25:39 25 4
gpt4 key购买 nike

这可以正常工作:

  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 ''return null 放在 else block 中,我总是得到 null,这是为什么?

最佳答案

您没有正确使用 arrayFirstarrayFirst 需要一个返回 truefalse 的函数,评估每个项目。返回函数返回 true 的第一项。它应该是这样的:

self.getById = function(id) {
return ko.utils.arrayFirst(self.PostArray(), function(item) {
return item.postId === id;
}) || 'not found';
};

如果 item 是错误的(在这种情况下很可能是 null),基本上返回 'not found'

参见 this article有关 KnockoutJS 中各种实用函数的更多信息。

关于javascript - ko.utils.arrayFirst 在不处理非空字符串的 else block 时总是返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21222480/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com