简体   繁体   English

未定义变量的JavaScript错误

[英]javascript error on undefined variable

I am bit confused on why I am getting 'msg' is undefined error (alert(msg) line) in below code. 我对为什么我在以下代码中得到“ msg”是未定义的错误(alert(msg)行)感到困惑。 if I have at least one incorrect address ( address: 0) then I would expect below code to set inValidUser =1 and also set msg variable and then break the the loop. 如果我至少有一个不正确的地址(地址:0),那么我希望下面的代码设置inValidUser = 1并设置msg变量,然后中断循环。 However, I then get a javascript error " Error: 'msg' is undefined." 但是,然后我收到一个JavaScript错误“错误:'msg'未定义”。 Any ideas? 有任何想法吗?

function test(userData) {
    var myArr = [];
    var i;
    for (i = 1; i <= 3; i++) {
        myArr.push(
            jQuery.ajax({
            type: "GET",
            url: "http:/c.html/" + i,
            });
        );
    }

    $.when.apply($, myArr).done(function() {
        var i = 0;
        var invalidUser = 0;
        var tableData = [];

        $.each(arguments, function (idx, args) {
            if (args[0].address === 0) {
                invalidUser = 1;
                var msg = "User Address " + userData[j].address + " not correct";
                return false;
            } else {
                tableData.push({
                    name: userData[i].firstname,
                    age: userData[i].age
                });
            }
            i++;
        });
        if (invalidUser `enter code here`=== 1) {    
            alert(msg);
        } else {
            addTableData(tableData);
        }
    }).fail (function (jqXHR, textStatus) {
        //oops..failed
    });   
}

You have a scope error in your code. 您的代码中存在范围错误。 When you declare a variable with var , it will be bound to the closest function that the declaration statement appears in. 当使用var声明变量时,它将绑定到声明语句出现的最接近的函数。

In this case, it means this: 在这种情况下,这意味着:

    $.each(arguments, function (idx, args) {
    //                ^^^^^^^^             ^ this scope
        if (args[0].address === 0) {
            invalidUser = 1;
            var msg = "User Address " + userData[j].address + " not correct";
    //      ^^^ declares variable in new scope
            return false;
        } else {
            tableData.push({
                name: userData[i].firstname,
                age: userData[i].age
            });
        }
        i++;
    });

What you will want to do is make sure that msg is declared in a scope that both uses of msg have access to. 什么,你会想要做的就是确保msg是在范围的情况下都使用声明msg访问。 That would be: 那将是:

$.when.apply($, myArr).done(function() {
    var msg;
//  ^^^^^^^^
    var i = 0;
    var invalidUser = 0;
    var tableData = [];

here, in your case. 在这里,根据您的情况。

When you set msg , then, you would use a variable assignment expression, rather than a declaration: 设置msg ,将使用变量赋值表达式,而不是声明:

    msg = "User Address " + userData[j].address + " not correct";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM