最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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?

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?

Share Improve this question asked Jan 19, 2014 at 20:50 formatcformatc 4,3237 gold badges46 silver badges83 bronze badges 1
  • Knockout provides ko.utils.arrayFirst that will execute a function against each item in our array and returns the first item where the function evaluates to true. otherwise it returns null – Evon Dos Commented Aug 18, 2016 at 6:19
Add a comment  | 

1 Answer 1

Reset to default 20

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.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论