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