【问题标题】:Automatically updating the actual parameters in javascript自动更新javascript中的实际参数
【发布时间】:2012-06-17 15:57:05
【问题描述】:

调用java脚本方法时如何通过引用传递原始变量(如字符串)? 相当于 C# 中的 out 或 ref 关键字。

我有一个像 var str = "this is a string"; 这样的变量,并将 str 传递到我的函数中,当我更改参数值时,我必须自动反映 str 的变化

function myFunction(arg){
    // automatically have to reflect the change in str when i change the arg value
    arg = "This is new string";
    // Expected value of str is "This is new string"
}

【问题讨论】:

标签: javascript


【解决方案1】:

原始类型,即字符串/数字/布尔值是按值传递的。 函数、对象、数组等对象是通过引用“传递”的。

因此,您想要的将无法实现,但以下方法将起作用:

        var myObj = {};
        myObj.str = "this is a string";
        function myFunction(obj){
            // automatically have to reflect the change in str when i change the arg value
            obj.str = "This is new string";
            // Expected value of str is "This is new string"
        }
        myFunction(myObj);
        console.log(myObj.str);

【讨论】:

  • 这大部分是正确的,但pedants will tell you that JavaScript is pure pass-by-value,并且为对象传递的 本身就是一个引用。然而,这很令人困惑,从实际的角度来看,它基本上看起来就像是通过引用传递对象。
  • 嗯,是的,这就是我真正想说的。
猜你喜欢
  • 1970-01-01
  • 2011-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多