Javascript的参考价值

这个问题在这里已经有了答案:

  • JavaScript是传递引​​用还是传值语言? 29个答案

  • 我的理解是,这其实很简单:

  • Javascript总是按值传递,但是当一个变量引用一个对象(包括数组)时,“值”是对该对象的引用。
  • 改变一个变量的值永远不会改变底层基元或对象,它只是将变量指向一个新的基元或对象。
  • 但是,更改由变量引用的对象的属性确实会更改基础对象。
  • 所以,通过你的一些例子:

    function f(a,b,c) {
        // Argument a is re-assigned to a new value.
        // The object or primitive referenced by the original a is unchanged.
        a = 3;
        // Calling b.push changes its properties - it adds
        // a new property b[b.length] with the value "foo".
        // So the object referenced by b has been changed.
        b.push("foo");
        // The "first" property of argument c has been changed.
        // So the object referenced by c has been changed (unless c is a primitive)
        c.first = false;
    }
    
    var x = 4;
    var y = ["eeny", "miny", "mo"];
    var z = {first: true};
    f(x,y,z);
    console.log(x, y, z.first); // 4, ["eeny", "miny", "mo", "foo"], false
    

    例2:

    var a = ["1", "2", {foo:"bar"}];
    var b = a[1]; // b is now "2";
    var c = a[2]; // c now references {foo:"bar"}
    a[1] = "4";   // a is now ["1", "4", {foo:"bar"}]; b still has the value
                  // it had at the time of assignment
    a[2] = "5";   // a is now ["1", "4", "5"]; c still has the value
                  // it had at the time of assignment, i.e. a reference to
                  // the object {foo:"bar"}
    console.log(b, c.foo); // "2" "bar"
    

    Javascript总是按价值传递。 但是,如果将对象传递给函数,则“值”实际上是对该对象的引用,因此该函数可以修改该对象的属性,但不会使该函数外部的变量指向某个其他对象。

    一个例子:

    function changeParam(x, y, z) {
      x = 3;
      y = "new string";
      z["key2"] = "new";
      z["key3"] = "newer";
    
      z = {"new" : "object"};
    }
    
    var a = 1,
        b = "something",
        c = {"key1" : "whatever", "key2" : "original value"};
    
    changeParam(a, b, c);
    
    // at this point a is still 1
    // b is still "something"
    // c still points to the same object but its properties have been updated
    // so it is now {"key1" : "whatever", "key2" : "new", "key3" : "newer"}
    // c definitely doesn't point to the new object created as the last line
    // of the function with z = ...
    

    是的,Javascript总是按值传递,但是在数组或对象中,值是对它的引用,所以你可以“更改”内容。

    但是,我想你已经阅读过它; 在这里你有你想要的文档:

    http://snook.ca/archives/javascript/javascript_pass

    链接地址: http://www.djcxy.com/p/469.html

    上一篇: Javascript by reference vs. by value

    下一篇: How do I convert a String to an int in Java?