ko.utils.arrayFirst 在不处理非空字符串的 else 块时始终返回 null

2024-03-31

这可以正确工作:

  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(使用前将#替换为@)

ko.utils.arrayFirst 在不处理非空字符串的 else 块时始终返回 null 的相关文章

随机推荐