JavaScript:全局数组变量返回未定义

标签 javascript arrays undefined

这里是 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 , dbwb .这些是局部作用域为 run 的变量功能。

然后调用 getData并将这些数组作为参数传递。

内部getData声明了新的局部变量(也称为 hourdbwb),并为其分配了调用函数时传递的三个空数组。

然后该函数会忽略这些值并用新数组(这些数组有内容)覆盖它们。

然后它返回另一个包含每个数组的新数组。

这让我们回到 run . getData 的返回值被完全忽略并访问原始数组(它们仍然存储在属于 hourdbwbrun 变量中)(但它们仍然是空的)。

您可以:

  • 操作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/

相关文章:

arrays - 索引 MongoDB 数组位置查询

c++ - 未定义的函数引用错误?

javascript - Wordpress 为不同的表格自定义加载更多按钮

javascript - 如何向此幻灯片脚本添加不透明度过渡?第2部分

arrays - 如何在 Apache Spark 中分解 get_json_object

PHP - 将字符串添加到数组

javascript - JavaScript 循环迭代中的 POST 之间需要延迟

javascript - create-react-app 构建不接受样式

javascript - 在 javascript 中迭代项目的最佳方法是什么?

JavaScript 未定义的疯狂