Assigning objects in Javascript: shallow or deep copy?

This question already has an answer here:

  • Javascript by reference vs. by value [duplicate] 4 answers

  • As alluded in the comments, JavaScript operates entirely on references, the only exception being that primitive values are kept on the stack and a program does not therefore require a reference to access them. In your example all variable declarations create new values - each an instance of Array - however what is returned from declaring an array is a reference, not the array itself. For example, [1, 2] is an array of values (integers), but [a, b] is an array of references.

    So... nothing is copied . We can demonstrate this by placing an object as an element of an array and inspecting that a previously assigned property is still accessible through the new 'parent' array.

    (And to answer your question in the comments, yes, your example is more performant than if you (or JavaScript) were to copy values.)

    'use strict';
    
    const arrayOne = [];
    
    arrayOne.someProperty = "This string is a property of `arrayOne`, " +
                            "accessed via the reference to it in `arrayTwo`."
    
    const arrayTwo = [arrayOne];
    
    span.innerHTML = arrayTwo[0].someProperty;
    <span id="span"></span>
    链接地址: http://www.djcxy.com/p/20980.html

    上一篇: OO对象的Javascript副本

    下一篇: 使用Javascript分配对象:浅层还是深层复制?