在javascript中设置全局数组的值

时间:2014-03-20 05:08:56

标签: javascript jquery arrays

$(document).ready(function(){
var currArray=null;
var group=null;
var admin=null;
var equipment=null;
var student=null;
console.log("after get array info");
for(var i=0; i<equipment.length; i++)
{
    console.log("equipment at index after get array info: "+i+" val: "+equipment[i]);
}
setArray();

console.log("finished initial");
function getArrayInformation()
{
    console.log("Get array information");
    //equipment=new Array("Item ID", "Model", "Series", "Manufacturer");
    $.post("Search", function(response)
            {
                console.log("back from Search AJAX");
                $.each(response, function(index, val)
                        {
                            console.log("index of .each for Search AJAX response: "+index+" value of this: "+val);
                            jsonParse(index, val);
                        });
            });
}
function jsonParse(index, val)
{
    if(index == "equipment")
        {
            console.log("setting equipment array");
            equipment = val.split(",");
            console.log("equipment array after creating it");
            for(var i=0; i<equipment.length; i++)
            {
                console.log("equipment at index: "+i+" val: "+equipment[i]);
            }
        }
    else if(index == "student")
        {
            student = val.split(",");
        }
    else if(index == "group")
    {
        group = val.split(",");
    }
    else if(index == "admin")
    {
        admin = val.split(",");
    }

}

正如你所看到的,我最初的变量设备等于null。然后在jsonParse中设置它。但是当我尝试在getArrayInformation函数完成后打印出其中的值时,Firefox中的javascript控制台表示它为空。

我很困惑为什么这么说。我唯一能想到的是它只是在jsonParse函数中设置为本地使用。如果事实上只是在本地,那么我应该将其设置为全局(在document.ready中)使用吗?

1 个答案:

答案 0 :(得分:0)

问题是$.post是异步的(请参阅https://api.jquery.com/jQuery.post/)。因此,当脚本尝试访问equipment变量时,它尚未初始化。您可能希望将代码放在$.post回调中:

$.post("Search", function(response) {
  console.log("back from Search AJAX");
  $.each(response, function(index, val) {
    console.log("index of .each for Search AJAX response: "+index+" value of this: "+val);
    jsonParse(index, val);

    // Your code below
    for(var i=0; i<equipment.length; i++) {
      console.log("equipment at index after get array info: "+i+" val: "+equipment[i]);
    }
  });
});