ko.utils.arrayFirst always returns null when not handling else block with non-empty string

怎甘沉沦 提交于 2019-12-13 13:01:53

问题


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?


回答1:


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:

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).

See this article for more information on the various utility functions in KnockoutJS.



来源:https://stackoverflow.com/questions/21222480/ko-utils-arrayfirst-always-returns-null-when-not-handling-else-block-with-non-em

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!