简体   繁体   English

如何在javascript中更改函数中变量的值?

[英]How to change the value of variable in a function in javascript?

var e = 15;

function change_value(e){

    e = 10;
}

change_value(e);

console.log(e);

The Value of e is still 15. e 的值仍然是 15。

The e inside the function scope is different from the e inside the global scope.e功能范围内从不同e全局范围内。

Just remove the function parameter:只需删除函数参数:

var e = 15;

function change_value(){
    e = 10;
}

change_value();
console.log(e);

When you have a parameter in a function, the passed value is copied in the scope of the function and gets destroyed when the function is finished.当函数中有参数时,传递的值会在函数范围内复制,并在函数完成时销毁。

all variables in Javascript are created globally so you can just use and modify it without passing it: Javascript 中的所有变量都是全局创建的,因此您可以直接使用和修改它而无需传递它:

var e = 15;

function change_value(){

    e = 10;
}

change_value();

console.log(e);

javascript does not use reference for simple types. javascript 不使用简单类型的引用。 It use a copy method instead.它使用复制方法。 So you can't do this.所以你不能这样做。

You have 2 solutions.您有 2 个解决方案。 This way :这边走 :

var e = 15;

function change_value(e) {
    return 10;
}

e = change_value(e);

Or this one :或者这个:

var e = 15;

function change_value() {
    e = 10;
}

But note that this solution is not really clean and it will only works for this e variable.但请注意,这个解决方案并不是很干净,它只适用于这个e变量。

You can do something like this if you want to assign the passed value to the outer e variable.如果要将传递的值分配给外部 e 变量,则可以执行类似操作。 this is just a sample.这只是一个示例。 In the block you might have any logic in future.在块中,您将来可能会有任何逻辑。

var e = 15;
function change_value(e){

    return e;
}

e = change_value(10);

console.log(e);

But if you want to only call the function and change the e value then remove the parameter from the function because it has different scope then the outer one.但是,如果您只想调用函数并更改 e 值,则从函数中删除参数,因为它的作用域与外部作用域不同。

 var e = 15;
 function change_value(){

   e = 10;
}

change_value(10);

console.log(e);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM