2013-03-01 51 views
1

你知道爲什麼這個函數會中斷嗎?

我使用窗口檢索全局數組的值。 我使用console.log獲取了arr對象值 但是,如果我嘗試在foreach中使用arr對象,則會破壞代碼。 任何想法爲什麼?

function setDropDownList(raw_id, val){ 
    // Get the ID 
    var the_id = '#'+raw_id; 
    // Get the array name as a string 
    var arrname = val+"Array"; 
    // get the arr object using the arrname string 
    var arr = window[arrname]; 
    // if I place a console.log here, i get the values for the arr object, but it brakes the .each below: 

    // do a simple foreach 
    // using arr breaks the foreach loop 
    // if I use the actual array declared globally in he header it works. 
    jQuery.each(arr, function(key, value) { 
     var test = value.split('|'); 
    }); 
} 
+0

「it break」是什麼意思? '.each'會發生什麼? * * console.log(arr)'print? – 2013-03-01 18:53:18

+0

確實它是如何打破的? – 2013-03-01 18:53:33

+0

如果沒有$ .each,那麼console.log(arr)會顯示arr對象。當我執行循環時,console.log()用於arr顯示:undefined – user2065483 2013-03-01 18:53:55

回答

1

這是因爲數組中的一個(或全部)項不是字符串。

當你做value.split('|')時,它要求該值是一個字符串。否則,它會中斷。

+0

我只使用數字進行測試......我從來沒有考慮過這一點。這就是爲什麼你有16.1 k的經驗 – user2065483 2013-03-01 18:58:36

+0

我只是在真正的專家擁擠的地方只是一個新手。很高興我的回答對你有所幫助。 – techfoobar 2013-03-01 19:01:48

+0

我已經改變了數組,仍然沒有工作......除了我可以使用的另外一種方法嗎?如果我直接輸入數組,而不是arr,它可以工作。 – user2065483 2013-03-01 19:05:28