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);

e的价值仍然是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);

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.


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);
链接地址: http://www.djcxy.com/p/51672.html

上一篇: 全局与局部变量的安全性?

下一篇: 如何在JavaScript中的函数中更改变量的值?