JS- 3 questions pavement week (the second week)

第二周,慢慢积累,做好准备,迎接蜕变

1. Introduction Under the difference between Set, Map, WeakSet and WeakMap of?

  • set

    • Set itself is a constructor to generate Set data structure.
    • The only member of the disorder is not repeated.
    • [Value, value], the key is consistent with the key name (or the only key, no key name).
    • You can traversal methods: add, delete, has more.
const set = new Set([1,2,2,3,3,3])
[...set]    // [1,2,3]
复制代码

    Examples of the properties and methods set

  • Attributes

    • Set.prototype.constructor: constructor, the default is Set function.
    • Set.prototype.size: Returns the total membership of the Set instance.
  • Method of operation

    • add (val): add some value, return Set structure itself.
    • delete (val): delete a value, it returns a Boolean value that indicates whether the deletion was successful.
    • has (val): returns a Boolean value that indicates whether the value is a member of Set.
    • clear (): remove all members and no return value.
  • Traversal methods

    • keys (): returns the key of the walker.
    • values ​​(): returns the key iterator.
    • entries (): returns the key-value pairs traversal.
    • forEach (): Use callback function to traverse each member.
  • WeakSet

    • Set WeakSet similar structure, it is not a duplicate set of values.
    • Members can only be an object, but can not be other types of values.
    • WeakSet the objects are weak references, that garbage collection is not considered WeakSet references to the object
    • Members WeakSet is not suitable reference, because it will disappear at any time, so we can not traverse
const a = [[1, 2], [3, 4]];
const ws = new WeakSet(a); // WeakSet {[1, 2], [3, 4]}
复制代码
  • method

    • WeakSet.prototype.add (value): add a new member to the instance of WeakSet.
    • WeakSet.prototype.delete (value): Clear the specified member WeakSet instance.
    • WeakSet.prototype.has (value): returns a Boolean value that indicates whether a value is in WeakSet instance.
  • Map

ES6 提供了 Map 数据结构。它类似于对象,也是键值对的集合,但是“键”的范围不限于字符串,各种类型的值(包括对象)都可以当作键。可以遍历,方法很多,可以和各种数据格式转换

const m = new Map();
const o = {p: 'Hello World'};

m.set(o, 'content')
m.get(o) // "content"

m.has(o) // true
m.delete(o) // true
m.has(o) // false

const map = new Map([
  ['name', '张三'],
  ['title', 'Author']
]);

map.size // 2
map.has('name') // true
map.get('name') // "张三"
map.has('title') // true
map.get('title') // "Author"
复制代码

Any parameters having Iterator interface, and each member of the data structure is an array of dual-element may as Map constructor. That is to say, Set, and Map can be used to generate a new Map.

const set = new Set([
  ['foo', 1],
  ['bar', 2]
]);
const m1 = new Map(set);
m1.get('foo') // 1

const m2 = new Map([['baz', 3]]);
const m3 = new Map(m2);
m3.get('baz') // 3
复制代码
  • Examples of properties and methods
    • size attribute: Returns the total membership of the Map structure.
    • set (key, value): Set key corresponding to the key name key is value, which then returns the entire Map structure.
    • GET (key) Method: reading the key corresponding to the key, if no key, returns undefined.
    • has (key) method: returns a Boolean value that indicates whether a key target in the current Map.
    • delete (key): Delete a key, returns true. If the deletion fails, it returns false.
    • clear () method: remove all members and no return value.
  • Traversal methods
    • keys (): returns the key of the walker.
    • values ​​(): returns the key iterator.
    • entries (): Returns all members of the walker.
    • () ForEach: Map of traversing all members.
const map = new Map([
  ['F', 'no'],
  ['T',  'yes'],
]);

for (let key of map.keys()) {
  console.log(key);
}
// "F"
// "T"

for (let value of map.values()) {
  console.log(value);
}
// "no"
// "yes"

for (let item of map.entries()) {
  console.log(item[0], item[1]);
}
// "F" "no"
// "T" "yes"

// 或者
for (let [key, value] of map.entries()) {
  console.log(key, value);
}
// "F" "no"
// "T" "yes"

// 等同于使用map.entries()
for (let [key, value] of map) {
  console.log(key, value);
}
// "F" "no"
// "T" "yes"
复制代码

Map structures into an array structure, relatively rapid operator can use the extended (...). E.g

const map = new Map([
  [1, 'one'],
  [2, 'two'],
  [3, 'three'],
]);

[...map.keys()] // [1,2,3]
复制代码
  • WeakMap

    • Map WeakMap similar structure and configuration, is used to generate a set of key-value pairs.
    • WeakMap only accept objects as keys (except the null), does not accept the values ​​of other types as keys.
    • WeakMap key name is pointing to objects, not included in garbage collection.
    • Can not traverse, the method with get, set, has, delete

WeakMap的专用场合就是,它的键所对应的对象,可能会在将来消失。WeakMap结构有助于防止内存泄漏。

2. introduce depth-first traversal and breadth-first traversal, how?

This is a need to traverse the DOM tree

<div id="parent">

    <div id="child-1">
      <div id="child-1-1">
        <div id="child-1-1-1"></div>
        <div id="child-1-1-2"></div>
        <div id="child-1-1-3"></div>
      </div>

      <div id="child-1-2">
        <div id="child-1-2-1"></div>
        <div id="child-1-2-2"></div>
      </div>

      <div id="child-1-3"></div>
    </div>

    <div id="child-2"></div>

    <div id="child-3"></div>

  </div>
复制代码
  • Depth-first traversal DFS
    let deepTraversal = (node) => {
        let nodes = []
        if (node !== null) {
          nodes.push(node)
          let children = node.children
          for (let i = 0; i < children.length; i++) {
            nodes = nodes.concat(deepTraversal(children[i]))
          }
        }
        return nodes
      }
    
    let res = document.querySelector('#parent')
    
    console.log(deepTraversal(res))
复制代码

result

The initial state is assumed that the figures were not all vertices is accessed from a vertex v, firstly access the vertex followed from its various neighbors have not been accessed depth-first search graph traversal, until all the figures and v there are similarities path to vertices have been visited. If this fashion not have access to the other vertex, the vertex alternatively as a starting point it has not been accessed, repeating the process until all vertices have been drawing until accessed.

  • BFS breadth-first traversal
    let widthTraversal = (node) => {
      let nodes = []
      let stack = []
      if (node) {
        stack.push(node)
        while (stack.length) {
          let item = stack.shift()
          let children = item.children
          nodes.push(item)
            // 队列,先进先出
            // nodes = [] stack = [parent]
            // nodes = [parent] stack = [child1,child2,child3]
            // nodes = [parent, child1] stack = [child2,child3,child1-1,child1-2]
            // nodes = [parent,child1,child2]
          for (let i = 0; i < children.length; i++) {
            stack.push(children[i])
          }
        }
      }
      return nodes
    }
复制代码

result

A vertex v from FIG sequentially accessed v after visit v individual never visited neighbors, then separately from the abutment point sequentially access their neighbors, and so "is first vertex neighbors access prior to the adjacent vertex dots after access is accessed, until all of the figures have been adjacent vertices access points are accessed. at this time, if there are vertex figures have not been accessed, the access is never a need for an alternative over the apex as the new starting point to repeat the above process until all vertices have been drawing until accessed.

3. Shallow vs. deep copy

Online quoted a picture to explain the relationship between data types and shallow vs. deep copy of

JS in the value of two types:

  1. Basic types: string, number, boolean, undefined, null
  2. Complex basic types: object

Storage location:

  1. Basic types of values ​​stored in the stack (Stock), the size is determined, and is not changed. Stack (Stack) is automatically allocated memory space, it is automatically released by the system
  2. The basic types of complex values ​​stored in a heap, of uncertain size, can be changed, saved in the stack is the address of a pointer to heap real value. Heap (heap) is dynamically allocated memory, variable size are not automatically released.

Relations assignment, a shallow copy and deep copy

  • Basic data types assignment (=) in the newly opened section of the memory stack memory, are two completely unrelated objects.
var a = 1
var b = a
a++
console.log(a)  // 2
console.log(b)  // 1
复制代码
  • Reference type of assignment is pass-by, that is a reference type is assigned an address assignment object stored in the stack, so if two variables point to the same object, and thus influence each other between the two operations.
var a = {num:1}
var b = a

a.num = 2
console.log(a.num)  // 2
console.log(b.num)  // 2
复制代码
  • The source object copied to the target object, but not including the sub-objects of the source object

  • The source object copied to the target object, the source object comprising sub-objects

Comparative data for the basic type of complex, three operations

operating And whether the original data point to the same object The first layer is a data base data type Sub-objects contained in the original data
Assignment Yes Change will alter the original data Change will alter the original data
Shallow copy no Change does not change the original data Change will alter the original data
Deep copy no Change does not change the original data Change does not change the original data

Achieve shallow copy

  1. Object.assign(target, source, source...)
    function shallowCopy(src) {
        var dst = {};
        for (var prop in src) {
            if (src.hasOwnProperty(prop)) {
                dst[prop] = src[prop];
            }
        }
        return dst;
    }
复制代码

Implement deep copy

JSON.parse (JSON.stringify (obj)) to achieve a deep copy limitations it is, when there is other data or undefined function data, can not be achieved.

    function deepClone(obj) {
        // 因为typeof null == "object" 但 null并不是对象,是基本类型
        if (obj == null) return
        var res = Array.isArray(obj) ? [] : {}
        
        for (key in obj) {
            if (obj.hasOwnProperty(key)) {
                if ( typeof obj[key] == "object" ) {
                    res[key] = deepClone(obj[key])
                } else {
                    res[key] = obj[key]
                }
            }
        }
        return res
    }
复制代码

To test

    var source = {
        name: 'source',
        do: function (n) {
          console.log(n)
        },
        obj: {
          name: '子对象obj'
        }
      }
    
      var target = deepClone(source)
    
      target.name = 'target'
      target.do = function (n) {
        console.log(n * 2)
      }
      target.obj.name = '拷贝子对象成功'
    
      console.log(source)
      console.log(target)
复制代码

You can see the modified copy of the object and sub-object does not have an impact on the source object, copy success.

欢迎指正和交流

Reproduced in: https: //juejin.im/post/5cf478715188251a9c4cf961

Guess you like

Origin blog.csdn.net/weixin_34221276/article/details/91480863