js value type and reference type

A classic problem: The following two outputs of the outcome inconsistent?

    // 情况1:值类型
    let a = 100
    let b = a
    b = 20
    console.log(a)  // 100

    // 情况2:引用类型
    let a = { age: 100 }
    let b = a
    b.age = 20
    console.log(a.age)  // 20

Answer:
case b is 1 值类型, while in the case of b is 2 引用类型.

Value type:

  • The value of a variable of type space is fixed, it is stored in the stack.
  • A value type and the variable b can be seen as a uncorrelated variables.
  • b changes do not affect the value of a stored value is copied with itself.
  • Using detection data type typeof

Reference types:

  • Reference type variable space is not fixed, stored on the heap.
  • Reference type variable b with a point to the same memory address.
  • b changes will affect the value of a stored copy of the object is a pointer to a pointer.
  • Using the detected data type instanceof

Come out of the problem: JS in which variables are value types, which is a reference type variable?

Common value types:

let a  // undefined,注意:未定义的变量不可用const定义
const s = 'abc'  // 字符串
const n = 100  // 数字
const b = true  // bool
const s = Symbol('s')  // symbol

Common reference types:

const obj = { x: 100 }  //对象
const arr = ['a', 'b', 'c']  //数组
const n = null  // 特殊引用类型,指针指向空地址
Published 673 original articles · won praise 644 · views 380 000 +

Guess you like

Origin blog.csdn.net/zhaohaibo_/article/details/104465989