【问题标题】:Define a variable that has been put in the function arguments in Javascript在 Javascript 中定义一个已放入函数参数中的变量
【发布时间】:2014-01-04 22:09:03
【问题描述】:

我正在尝试定义一个已在函数的参数中选择的变量,但它不会更改我在参数中使用的变量。

我的代码:

var x = "nothing yet!";

function changeValue(variable) {
    variable = "x";
}

changeValue(x);
console.log(x);

当我通过控制台运行它时,它只是显示为“还没有!”当我希望它显示为“x”时。

任何解决此问题的帮助都会非常有帮助。

【问题讨论】:

标签: javascript function variables console


【解决方案1】:

在 JavaScript 中 strings are primitive value types。您不能在这样的函数中更改它们。

它们也是不可变的。更改示例中的字符串就像更改数字 2 :)

为了强调这一点,对于 JavaScript - 你正在做的有点像:

function makeTwoThree(two){
    two = 3;
}
var two = 2;
makeTwoThree(two); // two is passed by value since it's a value type.

您应该将其退回:

function changeValue(variable) {
    return "x";
}
variable = changeValue(variable);

或者,您可以将它包装在一个对象中并传递可以让您更改引用的对象。但是,请记住,您不是在此处更改字符串,而是替换它。

【讨论】:

    【解决方案2】:

    你应该把它作为全局变量引用,这样做:

    var x = "nothing yet!";
    
    function changeValue(variable) {
        window[variable] = "x";
    }
    
    changeValue("x");
    console.log(x);
    

    这会将x 放入您的控制台。这是有效的,因为变量 x 是在全局范围内定义的(在任何函数之外)。您也可以这样做,因为如果它还需要在全局范围之外工作,那么在函数内部:

    (function() {
        var x = "nothing yet!";
    
        function changeValue(variable) {
            this[variable] = "x";
        }
    
        changeValue("x");
        console.log(x);
    })()
    

    该代码中的this 指的是调用它的作用域,因此在这种情况下,this[variable] 只是从调用它的函数中获取变量 x。

    【讨论】:

    • 这不是 OP 想要完成的,您现在将变量 name 传递给函数而不是变量。另外,如果上面的代码不在全局范围内,这将不起作用。此外,全局变量是邪恶的 :)
    猜你喜欢
    • 2014-10-15
    • 2014-03-13
    • 2013-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多