Passing a global variable to a function

前端 未结 5 1709
被撕碎了的回忆
被撕碎了的回忆 2020-12-03 03:41

How come the following code is giving me a 0 instead of a 1? I want my function to change a variable declared outside the function but I do not want to specify the variable

5条回答
  •  有刺的猬
    2020-12-03 04:25

    As answered by Oriol, it doesn't work because the variable is passed by value, so you're not changing the "that" variable. A workaround would be to pass the variable name :

    that = 0;
    
    function test(input) {
        window[input]++;
    }
    
    test("that");
    
    console.log(that); // 1
    

提交回复
热议问题