如何删除" undefined" Knockout可观察数组中的索引?

时间:2017-06-16 22:34:31

标签: javascript knockout.js

            self.previewApplicationsScreeningQuestions = ko.computed(function () {
                return ko.utils.arrayMap(self.applications(), function (i) {
                    if (i.application.applicationKey == self.previewApplicationKey())
                        return i.application.applicantScreeningQuestionsAndResponses[0];
                });
            });

我声明了一个像这样的viewModel。它的作用是,它基本上循环通过"应用程序" viewModel并返回其" applicantScreeningQuestionsAndResponses [0]"满足特定条件时的对象(在此问题中不重要)。

当我在控制台中查看结果时,它会给我。

[Object, undefined, undefined, undefined, undefined, undefined, undefined]

我只想删除所有未定义的索引,并在viewModel中保留一个[Object]。我该如何解决这个问题?

编辑:

            self.previewApplicationsScreeningQuestions = ko.computed(function () {
                return ko.utils.arrayMap(self.applications(), function (i) {
                    if (i.application.applicationKey == self.previewApplicationKey())
                        var arr = i.application.applicantScreeningQuestionsAndResponses[0];
                });
                var newArr = new Array();
                for (var i = 0; i < arr.length; i++) {
                    if (arr[i]) {
                        newArr.push(arr[i]);

                    }

                }
                return newArr;
            });

这将返回所有未定义的&#39;

1 个答案:

答案 0 :(得分:0)

你可以写下面的内容:

 self.previewApplicationsScreeningQuestions = ko.computed(function () {
            return ko.utils.arrayMap(self.applications(), function (i) {
                if (i.application.applicationKey == self.previewApplicationKey() && i.application.applicantScreeningQuestionsAndResponses[0]!=undefined)
                    return i.application.applicantScreeningQuestionsAndResponses[0];
            });
        });