为什么我的返回值未定义(JavaScript)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17276561/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 07:44:59  来源:igfitidea点击:

Why is my return value undefined (JavaScript)

javascriptarraysobjectreturn

提问by Ben

I have an array called questionSets full of objects. The createSet function should create new or create a copy of an existing questionSets object. The function getQuestionsFromSet is used if createSet is used to make a copy. For some reason when I call getQuestionsFromSet() from inside createSet() I always get a returned value of 'undefined'. I can't figure out why because when I do a console.log() of the value to be returned by getQuestionsFromSet() I see exactly what I want.

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

I have these two functions.

我有这两个功能。

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

回答by techfoobar

Because getQuestionsFromSet()does not returnanything and so is implicitly undefined.

因为getQuestionsFromSet()没有return任何东西,所以是隐式undefined

What you need is probably something like:

你需要的可能是这样的:

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
}

回答by haim770

return obj.value;is nested within the inner $.each(function{}), and getQuestionsFromSetis indeed not returning anything.

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