在Javascript中设置全局数组的值不起作用

时间:2019-02-14 10:49:29

标签: javascript arrays setvalue

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

pixels

但是控制台输出是“ undefined”,我想知道为什么吗?应该根据prepare()中的参数为local_Pl设置一个getInfo值,该值必须为“ 5”:

    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();

为什么不起作用?

1 个答案:

答案 0 :(得分:1)

您将pllocal_Pl用作out参数,又称为pass by reference参数或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);
}