最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Changing variable in another function in JavaScript - Stack Overflow

programmeradmin0浏览0评论

I'm pretty new to JavaScript and I'm having trouble with some of the properties of variables and functions.

What I want to happen is have a var defined in one function, have the value changed in another, and then have the new value returned to the function where it was originally defined.

Here is a simple sample that I made:

function getIt(){
    var x = 3;
    doubleIt(x);
    alert("The new value is: " + x);
}

function doubleIt(num){
    num *= 2;
    return num;
}

When this is run the alert still displays the original value of x. Is there a syntax to have the value in the original function changed?

I'm pretty new to JavaScript and I'm having trouble with some of the properties of variables and functions.

What I want to happen is have a var defined in one function, have the value changed in another, and then have the new value returned to the function where it was originally defined.

Here is a simple sample that I made:

function getIt(){
    var x = 3;
    doubleIt(x);
    alert("The new value is: " + x);
}

function doubleIt(num){
    num *= 2;
    return num;
}

When this is run the alert still displays the original value of x. Is there a syntax to have the value in the original function changed?

Share Improve this question edited May 13, 2019 at 13:06 Matthew Smith 5087 silver badges24 bronze badges asked Mar 24, 2012 at 21:06 user1290426user1290426 1533 silver badges7 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

The simplest method would be to assign the result back to the variable

x = doubleIt(x);

Demo: http://jsfiddle/ES65W/


If you truly want to pass by reference, you need an object container to carry the value. Objects are passed by reference in JavaScript:

function getIt(){
    var myObj={value:3};
    doubleIt(myObj);
    alert("the new value is: " + myObj.value);
}

function doubleIt(num){
    num.value *=2;
    //return num;
}

Demo: http://jsfiddle/dwJaT/

发布评论

评论列表(0)

  1. 暂无评论