关联数组设置不正确



我是JavaScript和jquery的新手,想知道是否有人可以让我了解为什么这不能正常工作。

我有一个下拉框,用户从中选择一个值,然后选择"进程"。处理时,下拉列表的值以及文本框存储在数组中。 我希望用户能够基本上再次在数组中存储相同的下拉选择和文本框数据,但现在存储在新的值对中。

第一家商店将是TestArray[0][0] = "文本框值"

如果再次"处理",它将是TestArray[1][0] = "Textbox Value"

这样我以后就可以解析并计算用户"处理"下拉选择的次数;

var oneClickReport = $("#reportName").val();
    if(oneClickReport == "Sample Report One"){
        var arrayOneCount = reportOneArray.length;
        var totalHouseholds = 0;
            $("#reportChecks span:visible").each(function(){            
                if($(this).find(':checkbox').prop('checked')){
                    var HHName = $(this).text();
                    reportOneArray.push(HHName);
                    arrayTest[arrayOneCount][totalHouseholds] = HHName;
                }
            totalHouseholds += 1;
            });
            for(i = 0; i < arrayOneCount; i+=1){
                alert(arrayTest[0][i]);
            }
    }

但是当第二次尝试"处理"时,我收到错误;

SCRIPT5007: Unable to set property '0' of undefined or null reference 

在线;

arrayTest[arrayOneCount][totalHouseholds] = HHName;

您需要初始化数组。我不确定你到底想做什么,但你需要这样的数组

var arrayTest = []

您将需要初始化后续值,例如

arrayTest[1] = []

然后,您可以访问阵列

arrayTest[1][0] = []

我为你做了一个例子

var oneClickReport = $("#reportName").val();
var arrayTest = [] # You may need to put this elsewhere
if(oneClickReport == "Sample Report One"){
    var arrayOneCount = reportOneArray.length;
    var totalHouseholds = 0;
        $("#reportChecks span:visible").each(function(){            
            if($(this).find(':checkbox').prop('checked')){
                var HHName = $(this).text();
                reportOneArray.push(HHName);
                if(!arrayTest[arrayOneCount]){ arrayTest[arrayOneCount] = []; }
                arrayTest[arrayOneCount][totalHouseholds] = HHName;
            }
        totalHouseholds += 1;
        });
        for(i = 0; i < arrayOneCount; i+=1){
            alert(arrayTest[0][i]);
        }
}

您的var arrayOneCount = reportOneArray.length;问题,并且您没有更改此值

最新更新