简体   繁体   中英

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.

The e inside the function scope is different from the e inside the global scope.

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:

var e = 15;

function change_value(){

    e = 10;
}

change_value();

console.log(e);

javascript does not use reference for simple types. It use a copy method instead. So you can't do this.

You have 2 solutions. 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.

You can do something like this if you want to assign the passed value to the outer e variable. 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.

 var e = 15;
 function change_value(){

   e = 10;
}

change_value(10);

console.log(e);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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