【问题标题】:Why is my return value undefined (JavaScript) [duplicate]为什么我的返回值未定义(JavaScript)[重复]
【发布时间】:2013-06-21 00:34:29
【问题描述】:

我有一个名为 questionSets 的数组,里面装满了对象。 createSet 函数应该创建新的或创建现有 questionSets 对象的副本。如果使用 createSet 进行复制,则使用函数 getQuestionsFromSet。出于某种原因,当我从 createSet() 内部调用 getQuestionsFromSet() 时,我总是得到一个返回值“未定义”。我不知道为什么,因为当我对 getQuestionsFromSet() 返回的值执行 console.log() 时,我看到的正是我想要的。

我有这两个功能。

function createSet(name, copiedName) {
    var questions = [];
    if (copiedName) {
        questions = getQuestionsFromSet(copiedName);
    }
    console.log(questions); // undefined. WHY??
    questionSets.push({
        label: name,
        value: questions
    });
}; // end createSet()

function getQuestionsFromSet(setName) {
    $.each(questionSets, function (index, obj) {
        if (obj.label == setName) {
            console.log(obj.value); // array with some objects as values, which is what I expect.
            return obj.value;
        }
    });
}; // end getQuestionsFromSet()

【问题讨论】:

  • console.log 显示值?
  • @AnkitJaiswal 那里没有 Ajax 调用!

标签: javascript arrays object return


【解决方案1】:

因为getQuestionsFromSet() 没有return 任何东西,所以隐含未定义

你需要的可能是这样的:

function getQuestionsFromSet(setName) {
    var matched = []; // the array to store matched questions..
    $.each(questionSets, function (index, obj) {
        if (obj.label == setName) {
            console.log(obj.value); // array with some objects as values, which is what I expect.
            matched.push(obj.value); // push the matched ones
        }
    });
    return matched; // **return** it
}

【讨论】:

    【解决方案2】:

    return obj.value; 嵌套在内部$.each(function{}) 中,而getQuestionsFromSet 确实没有返回任何内容。

    【讨论】:

      猜你喜欢
      • 2013-01-31
      • 2018-03-08
      • 2017-05-19
      • 2021-11-15
      • 1970-01-01
      • 2015-12-16
      • 2021-10-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多