[Consolidation] js value types and reference types

Examples

Value Type

let a = 100;
let b = a;
a = 200;
console.log(b); // 100 (互不影响)

Reference types

let a = { age: 20 };
let b = a;
a.age= 21;
console.log(b.age); // 21 (b.age随a.age的改变而改变)

Storage

Value Type


js variables stored on the stack, as to how we store the first matter(After all, I do not know)This is js engine thing.
As illustrated, key the variable name, value of memory contents in value, the change does not affect the value of a value b value type variable values are stored directly.

Reference types


In the stack, the memory reference type of the memory address, while the value of the memory address points to the heap,
Briefly: a reference type -> memory address 1 -> value of a time if performed let b = a;, it is the memory b address points to a memory address, the memory address point to the same value, so when a change in value, the value of b has changed.

Source: learning materials

Why put forward a reference to the type of memory address?
As we all know is the most common reference type objects and arrays, the array length and object attributes is no limit to the number of, or even can be nested, if stored as reference images stored value type type (no memory address stored directly on the stack), and that the computer afraid to explode.

Common value types and reference types

// 常见值类型
let a; // undefined
const n = 100; // Number
const s = '100'; // String
const b = true; // Boolean
const s = Symbol('s') // Symbol(es6)
// 常见引用类型
const obj = { value: 100 }; // Object
const arr = [ 1, 2, 3 ]; // Array
const n = null; // 特殊引用类型,指针指向空地址
function fn() {} // 特殊引用类型,但不用于存储数据,所以不考虑深拷贝浅拷贝的问题

Deep copy

  • JSON.parse (JSON.stringify (obj))
    The easiest way, but ignores undefined, function, RegExp

  • Object.assign () or destructuring assignment ( const a = {...obj}, const b = [...arr])
    is only suitable for not only one layer or nested array of objects

  • Recursive (code from the network)
const deepCopy = obj => {
    let copy = Array.isArray(obj) === true ? [] : {}
    for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
            if (typeof obj[key] === 'object') {
                copy[key] = deepCopy(obj[key])
            } else {
                copy[key] = obj[key]
            }
        }
    }
    return copy
}

Guess you like

Origin www.cnblogs.com/deepdarkdeveloper/p/11888448.html