在JavaScript中的另一个函数中更改变量 [英] Changing variable in another function in JavaScript

查看:117
本文介绍了在JavaScript中的另一个函数中更改变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对JavaScript还是很陌生,并且在变量和函数的某些属性方面遇到了麻烦.

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

我想做的是在一个函数中定义一个var,在另一个函数中更改该值,然后将新值返回到最初定义该函数的位置.

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

运行时,警报仍显示x的原始值.是否有语法可以更改原始函数中的值?

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?

推荐答案

最简单的方法是将结果分配回变量

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

x = doubleIt(x);

演示: http://jsfiddle.net/ES65W/

如果您确实想通过引用传递,则需要一个对象容器来承载该值.对象是通过JavaScript中的引用传递的:

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

演示: http://jsfiddle.net/dwJaT/

这篇关于在JavaScript中的另一个函数中更改变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆