Hard Copy vs Shallow copy javascript

This question already has an answer here:

  • Is JavaScript a pass-by-reference or pass-by-value language? 29 answers

  • Objects and arrays are treated as references to the same object. If you want to clone the object, there are several ways to do this.

    In later browsers, you can do:

    var b = Object.assign({}, a);
    

    If you want to go for a library, lodash provides _.clone (and _.cloneDeep ):

    var b = _.clone(a);
    

    If you don't want to do either of those methods, you can just enumerate through each key and value and assign them to a new object.

    Oftentimes it's valuable for them to be treated as references when passing through multiple functions, etc. This isn't the case for primitives like numbers and strings, because that would feel pretty counterintuitive in most cases.

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

    上一篇: 修改函数中的变量

    下一篇: 硬拷贝vs浅复制JavaScript