[英]Define a variable that has been put in the function arguments in Javascript
我正在尝试定义一个在函数的参数中选择的变量,但它不会更改在参数中使用的变量。
我的代码:
var x = "nothing yet!";
function changeValue(variable) {
variable = "x";
}
changeValue(x);
console.log(x);
当我通过控制台运行它时,它只是“什么都没有!” 当我希望它以“ x”的形式出现时。
解决该问题的任何帮助将非常有帮助。
在JavaScript中, 字符串是原始值类型 。 您不能从这样的函数中更改它们。
它们也是不可变的。 更改示例中的字符串就像更改数字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);
或者,您可以将其包装在一个对象中并传递该对象,以使您可以更改引用。 但是,请记住,您不是在这里更改字符串,而是在替换它。
通过执行以下操作,您应该将其引用为全局变量:
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。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.