这里是 JavaScript 新手。我已经搜索并搜索了答案,但似乎无法弄清楚。我传递给函数的数组没有作为引用正确传递。我不认为这是许多帖子提到的异步问题,但我可能是错的。
我有要传递给函数的全局数组。在函数内部,数组返回它们正确的值,但是当我尝试在函数外部访问它们时,它们是未定义的。
对于上下文,我传递了 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];
};
最佳答案
run
将空数组分配给 hour
, db
和 wb
.这些是局部作用域为 run
的变量功能。
然后调用 getData
并将这些数组作为参数传递。
内部getData
声明了新的局部变量(也称为 hour
、db
和 wb
),并为其分配了调用函数时传递的三个空数组。
然后该函数会忽略这些值并用新数组(这些数组有内容)覆盖它们。
然后它返回另一个包含每个数组的新数组。
这让我们回到 run
. getData
的返回值被完全忽略并访问原始数组(它们仍然存储在属于 hour
的 db
、 wb
和 run
变量中)(但它们仍然是空的)。
您可以:
- 操作
getData
中的现有数组而不是覆盖它们。 (例如hour = [1,2,3]
可能变成hour.push(1); hour.push(2); hour.push(3)
)。 - 使用
getData
的返回值(在这种情况下,您首先不需要费心分配值或传递空数组)。您可以使用对象而不是数组,这样您也可以使用有用的名称而不是此处的顺序。
这样的:
function run(){
var cities = ["AB Edmonton","MI Detroit"];
var data = getData(cities);
alert(data.hour[1]);
}
function getData(cities){
//i= drop-down selection index, set to zero for testing
var i=0; // Use locally scoped variables where possible
var hour, db, wb;
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: hour, db: db, wb: wb];
};
关于JavaScript:全局数组变量返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30280271/