为什么在循环中返回时函数返回值未定义? [英] Why is function return value undefined when returned in a loop?

查看:140
本文介绍了为什么在循环中返回时函数返回值未定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道为什么会这样.

I can't figure out why this is happening.

以下函数始终返回未定义.即使满足条件,也应该返回一个值.

The following function always returns undefined. Even when the condition is satisfied and a value should be returned.

这是answerCollection变量的一个实例.

Here is an instance of the answerCollection variable.

[
Object
Answer: "2"
AnswerText: undefined
OpsID: "24"
PprID: "2"
Question: "How many colors?"
__proto__: Object
]

.

function GetAnswerForProcessQuestion(pprID)
    {
        $.each(answerCollection, function (index, item)
        {
            var thisPprID = item["PprID"];
            if (thisPprID == pprID)
            {
                var answer = item["Answer"];
                return answer;
            }
        });
    }

但是,如果我在循环内设置了一个变量,则在循环执行完后返回该变量,则返回正确的值.

However, if I set a variable inside the loop, then return that variable once the loop finishes executing, the correct value is returned.

function GetAnswerForProcessQuestion(pprID)
    {
        var answer;
        $.each(answerCollection, function (index, item)
        {
            var thisPprID = item["PprID"];
            if (thisPprID == pprID)
            {
                answer = item["Answer"];
            }
        });
        return answer;
    }

关于为什么我不能从循环中返回值的任何想法?

Any ideas on why I can't return a value from inside the loop?

推荐答案

$.each返回值不会从父函数返回该值.尝试通过以下方式进行操作:

Returning a value from $.each does not return the value from the parent function. Try doing it this way:

function GetAnswerForProcessQuestion(pprID)
    {
        var answer;
        $.each(answerCollection, function (index, item)
        {
            var thisPprID = item["PprID"];
            if (thisPprID == pprID)
            {
                answer = item["Answer"];
                return false; // break loop
            }
        });
        return answer;
    }

这篇关于为什么在循环中返回时函数返回值未定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆