如何将字符串转换为变量名称

时间:2014-06-06 09:20:16

标签: javascript jquery json

我正在加载多个外部JSON文件,并希望在显示下一个屏幕之前检查它们是否已成功缓存。我的策略是检查数组的名称,看它是否是一个对象。当我只检查一个数组并将数组名硬编码到我的函数中时,我的代码工作正常。我的问题是:我怎样才能让这种动态变化?

不动态:(这有效)

$("document").ready(){
    checkJSON("nav_items"); 
}

function checkJSON(){

   if(typeof nav_items == "object"){
       // success...
   }

}

动态:(这不起作用)

$("document").ready(){
    checkJSON("nav_items"); 
    checkJSON("foo_items"); 
    checkJSON("bar_items"); 
}

function checkJSON(item){

   if(typeof item == "object"){
       // success...
   }

}

这是我的代码的更大背景:

var loadAttempts = 0;  
var reloadTimer = false;  



$("document").ready(){
    checkJSON("nav_items"); 
}



function checkJSON(item){

loadAttempts++;

//if nav_items exists
if(typeof nav_items == "object"){

        //if a timer is running, kill it
        if(reloadTimer != false){
        clearInterval(reloadTimer);
        reloadTimer = false;
    } 
    console.log("found!!");
    console.log(nav_items[1]);
    loadAttempts = 0; //reset

            // load next screen....                   

} 

//if nav_items does not yet exist, try 5 times, then give up!
else {
            //set a timer
    if(reloadTimer == false){
        reloadTimer = setInterval(function(){checkJSON(nav_items)},300);
        console.log(item + " not found. Attempts: " + loadAttempts );
    }
            else {
        if(loadAttempts <= 5){
            console.log(item + " not found. Attempts: " + loadAttempts          );
        } else {
            clearInterval(reloadTimer);
            reloadTimer = false;
            console.log("Giving up on " + item + "!!");
        }
    }
}

}

2 个答案:

答案 0 :(得分:2)

根据数组的范围,您应该可以通过window[]访问它们:

$("document").ready(function() {
    checkJSON("nav_items"); 
});

function checkJSON(item) {
   if (typeof window[item] == "object") {
       alert(item + ' is an object');
   }
}

Example fiddle

答案 1 :(得分:1)

你必须传递object ...而不是string   .declare变量并分配json值

checkJSON(nav_items); 
 checkJSON(foo_items); 
 checkJSON(bar_items);