JavaScript newbie here。我搜索並搜索了答案,似乎無法弄清楚。我傳遞給函數的數組不能作爲引用正確傳遞。我不認爲這是一個像許多帖子暗示的異步問題,但我可能是錯的。我有傳遞給函數的全局數組。在函數內部,數組返回它們的正確值,但是當我嘗試在函數外部訪問它們時,它們是未定義的。JavaScript:全局數組變量返回undefined
對於上下文,我傳遞了3個數組,這些數組保存了幹球溫度,溼球溫度和進行測量以供稍後計算的小時。爲了簡潔起見,我只包含了一些示例數據點。下面的示例代碼:
function run(){
var hour = [];
var db = [];
var wb = [];
var cities = ["AB Edmonton","MI Detroit"];
getData(hour, db, wb, cities);
//this shows undefined, although within getData it is accurate data
alert(hour[1]);
}
function getData(hour, db, wb, cities){
//i= drop-down selection index, set to zero for testing
i=0;
switch(cities[i]) {
case "AB Edmonton":
hour = [1,2,3];
db = [15,18,21];
wb = [10,13,20];
break;
//case "MI Detroit":....
}
//this shows accurate values in the alert window
alert(cities[i] + " at hour:" + hour[i] + " the temp is:" + db[i]);
return [hour, db, wb];
};
可以傳遞城市到你的'getData'功能或定義它的功能外。就目前而言,城市只在'run'內定義,'getData'不能訪問它。確保查看關閉。 – Dom
但它們不是全局數組。你已經在run函數中指定了它們,所以它們只有這個範圍。 –
如果你沒有得到返回的數據,爲什麼你會返回它們? – Cristy