Let’s start with a couple of problems

  • Typeof determines which types
  • When to use === when to use ==
  • The difference between value types and reference types
  • Handwritten deep copy

knowledge

  • Value type vs reference type
  • The typeof operator
  • Deep copy

  1. Value type vs reference type

A stack is a place where variables are stored

Value types: small and can be stored directly on the stack; Undefined, null, string, number, Boolean, symbol (null is a primitive data type, but its pointer points to an empty address. Js defines the mechanical code label 0 as object, null is 0x000. Some are so large that the reference address is stored in the stack, while the actual value is stored in the heap. Objects, arrays, functions (functions: do not store data, so there is no such thing as copy copy functions, functions are executable code)Copy the code

  1. The typeof operator
  • Recognize all value types except null
  • Identify functions
  • Check if it is a reference type (reference type and NULL cannot be recognized)
    typeof null => 'object'
    typeof [] => 'object'
    typeof {x:1} => 'object'
Copy the code
  1. Deep copy (mostly recursive)

In addition to writing by hand, you can draw the process of storing values in deep copy yourself

const obj1 = { age: 20, name: 'xxx', address: { city: 'beijing' }, arr: ['a', 'b', 'c'] } const obj2 = deepClone(obj1) obj2.address.city = 'shanghai' obj2.arr[0] = 'a1' console.log(obj1.address.city) Console. log(obj1.arr[0]) /** * deep copy * @param {Object} obj */ function deepClone(obj = {}) {// Check whether obj is an Object or an array if (typeof obj ! = = 'object' | | obj = = null) {/ / if not directly return return obj} initialization / / return the result, Let result if (obj instanceof Array) {result = []} else {result = {}} for (let key in The obj) {// hasOwnProperty() method is used to check if a property is an object's own property and not inherited from the stereotype chain. If (obj. HasOwnProperty (key)) {return true if (obj. HasOwnProperty (key)) {return true if (obj. HasOwnProperty (key)) {return true if (obj. HasOwnProperty (key)) {return true if (obj. HasOwnProperty (key)); Result [key] = deepClone(obj[key])}}Copy the code