将全局变量传递给函数 [英] Passing a global variable to a function

查看:186
本文介绍了将全局变量传递给函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么以下代码给我0而不是1?我希望我的函数更改在函数外声明的变量,但我不想在函数声明中指定变量。

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 in the function declaration.

that = 0;

function go(input) {
    input++;
}

go(that);

console.log(that);


推荐答案

正如Oriol所回答,它不起作用,因为变量按值传递,因此您不会更改that变量。解决方法是传递变量名称:

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

这篇关于将全局变量传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆