首页 > 解决方案 > 在 Javascript 中为全局数组设置值不起作用

问题描述

我正在尝试根据函数调用的指定选项/值通过函数调用设置全局变量。这是我的代码:

    let g_Pl = [];

    function prepare() {
        let s = 0;

            s = 1;
            g_Pl[s] = 5;

            s = 2;
            g_Pl[s] = 8;

            s = 3;
            g_Pl[s] = 10;
        }

    function getInfo(s,map,pl) {
        switch (map) {
            case "test":
                pl = g_Pl[s];
            break;
        }
    }

function test() {
    let local_Pl;

    getInfo(1, "test", local_Pl)

    console.log(local_Pl);
}

prepare();
test();

但是控制台输出是“未定义的”,我想知道为什么?local_Pl 应该从 getInfo 中设置一个值,该值必须基于 prepare() 中的参数为“5”:

s = 1;
g_Pl[s] = 5;

为什么它不起作用?

标签: javascriptarrayssetvalue

解决方案


您使用plandlocal_Pl作为out参数又名pass by reference参数 or ByRef,但 JavaScript 不支持该功能。您应该返回结果,如下所示:

function getInfo(s, map) {
    switch (map) {
        case "test":
            return g_Pl[s];
    }
}

function test() {
    let local_Pl = getInfo(1, "test");
    console.log(local_Pl);
}

如果您需要返回一些东西并且还有一个 out 参数,那么您可以创建一个对象来包含两者并返回该对象。

function getInfo(s, map) {
    var element;
    switch (map) {
        case "test":
            element = g_Pl[s];
            break;
    }
    return { found: !!element, pl: element };
}

function test() {
    let result = getInfo(1, "test");
    if (result.found) console.log(result.pl);
}

推荐阅读