ES6 Symbol and Map

Symbol

A new data type in es6 that represents unique values

Basic data types: String Number Boolean null undefined Symbol

Reference data data type: Object

create:

let s1 = Symbol()
typeof s1      // 'symbol'

Notice:

1. Symbol cannot be called using new because symbol is a primitive type value, not an object.

2. The Symbol function accepts a string as a parameter, which only represents the description of the Symbol. It is mainly used to make it easier to distinguish when displaying on the console or converting to a string.

eg:

let s1 = Symbol()
let s2 = Symbol()
console.log(s1,s2).  //Symbol() Symbol()
let s3 = Symbol('js') 
let s4 = Symbol('html')
console.log(s3,s4) //Symbol(js) Symbol(html)
console.log(Symbol('html') === Symbol('html')) //false    参数仅仅是Symbol的描述,不代表其他意义

3. If the Symbol parameter is an object, the toString method of the object will be called, converted to a string and then a Symbol value will be generated.

eg:

const obj = {
    
    
  toString(){
    
    
    return 'abc'
  }
}
console.log(Symbol(obj))   // Symbol(abc)
const obj = {
    
    
  name: 'aa'
}
console.log(Symbol(obj))   //Symbol([object object])

Symbol type conversion

1.Convert to string
String(symbol('haha'))
2. Convert to Boolean
console.log(!!Symbol()) //true
3. Cannot be converted into numbers and cannot perform any operations.
console.log(Symbol('haha') + 'hello') //报错
4. As the attribute name of the object (because each Symbol value is not equal, this means that Symbol can be used as an identifier for the object)
let s = Symbol('s')
const data = {
    
    
  [s]: 'haha'
}
console.log(data)  //{Symbol(s): 'haha'}

Note: Symbol() as a property name cannot be traversed by for...in, for...of, nor can it be returned by Object.keys(), Object.getOwnPropertyNames(), but it is not a private property and can be obtained through the Object.getOwnPropertySymbols method. All Symbol property names of the object

eg:

let obj = {
    
    },
    foo = Symbol('foo')
Object.defineProperty(obj, foo, {
    
    
    value: 'footer'
})

for(let i in obj) {
    
    
    console.log(i)   //没有返回值
}
console.log(Object.getOwnPropertyNames(obj))  // []
console.log(Object.getOwnPropertySymbols(obj))  [Symbol(foo)]
const data = {
    
    
  [Symbol()]: 123
}
console.log(data)     //{Symbol():123}
console.log(data[Symbol()])  //undefined
console.log(Object.getOwnPropertySymbols(data))   //[Symbol()]
console.log(Object.getOwnPropertySymbols(data)[0])    // 123

Data structureSet

Similar to an array, the values ​​of the members are unique and there are no duplicate values.

1. How to create a Set

const set = new Set()

2.Attributes of Set class

var set = new Set([1,2,3,4])

set.size // 4

3. Methods of the Set class

1) set.add(value): Add a data and return the Set structure itself

​ set.add('a').add('b').add('c'). //Add multiple values

​ Or new Set([1,2,3])pass it in directly as a parameter

Note: set does not cast the stored value

​ set.add(5)

​ set.add(“5”)

Object.is(new Set().add(5), new Set().add('5'))   //false
2) set.delete(value): Delete the specified data and return a Boolean value to indicate whether the deletion is successful.

​ set.delete(‘a’) // true

​ set.delete(‘a’). // false

3) set.has(value): Determine whether the value is a Set member and return a Boolean value

​ console.log(set.has(‘a’)). //false

​ console.log(set.has(‘b’)). //true

4) set.clear(): clears all data and does not return a value
5) set.keys(): Returns the traverser of key names

​ const s = new Set([1,2,4])

​ console.log(s.keys())

6) set.values(): return value traverser

​ console.log(s.values())

7) set.entries(): returns a traverser of key-value pairs

​ console.log(set.entries())

8) set.forEach(): Use the callback function to traverse each member
var set = new Set([1,2,4])
set.forEach((value, key, ownerSet) = > {
    
        
     console.log(`${
      
      key}=${
      
      value}`)    
     console.log(ownerSet ===  set).  //true
})

Convert set to array:

const set = new Set([1,2,4])

[…set]

Array.from(set)

use:

a. Array deduplication

const arr = [{},1,2,3,1,4,'a',3]
console.log([...new Set(arr)])   //[{},1,2,3,4,'a']

b. Merge and remove duplicates

 let a = new Set([1,2,3]);
 let b = new Set([3,2,5]);
 let union = new Set([...a,...b]);
 console.log([...union]);    // [1,2,3,5]

Data structureMap

It is an ordered list that stores many key-value pairs. Keys and values ​​support all data types.

Previously: object could only use strings as keys

eg:

let data1 = {a: 1},    
    data2 = {b: 2}, 
    obj= {}
    obj[data1] = 1  
    obj[data2] = 2
    console.log(obj)    // {[object Object]: 2} 

Map can solve the above problems

var map = new Map().set({}, 1).set({}, 2)
console.log(map)  // {Object{}=>1, Object{}=>2}

1.Create Map

const map = new Map()

You can initialize parameters when creating. What is passed is a two-dimensional array. The array inside is in the form of key-value pairs.

const map = new Map([
	["a", 1],    
    ["b", 2]
])   

console.log(map).  // {"a" => 1, "b" => 2 }

2.Map attribute

map.size:The number of key-value pairs in the current data structure

3.Map method

1) set(key, value): Set the key value corresponding to the key name key to value, and return the entire Map structure. If the key already has a value, the key value will be updated, otherwise the key-value pair will be newly generated.

eg:

const map = new Map()
map.set('a',1).set('b',2).set('b',3)       /*链式写法*/
console.log(map).  //{"a" => 1, "b" => 3}
2.get(key): The get method reads the key value corresponding to the key. If the key cannot be found, undefined is returned.
console.log(map.get('a'))   //1
console.log(map.get('c'))   //undefined
3.delete(key): Delete a key, return true if the deletion is successful, otherwise return false
console.log(map.delete('a'))   // true
console.log(map.delete('d'))   // false
4.has(key): The method returns a Boolean value indicating whether a key is in the current Map object.
console.log(map.has('a'))   // false
console.log(map.has('b'))   // true
5.clear(): clear all data, no return value
map.clear()
map.size     //0
6) keys(): Returns the traverser of key names
7) values(): returns a traverser of values
8) entries(): returns a traverser of key-value pairs
9) forEach(): Use the callback function to traverse each member

Use for…of to traverse

const m = new Map()
m.set('a',1).set('b',2).set('c',3)
for(let [key, value] of map){
   consoel.log(key,value)    
}
Convert map to array:

[…map]

Array.from(map)

Convert map to object:
function strMapTObj(strMap){
	let obj = Object.create(null)
	for (let [k, v] of strMap){
      obj[k] = v
	}
	return obj
}
const map = new Map().set('yes', true).set('no', false)
strMapTObj(map)    // {yes: true, no: false}

Convert object to map:

function objToStrMap(obj) {
  let strMap = new Map()
  for (let k of Object.keys(obj)){
    strMap.set(k, obj[k])
  }
  return strMap
}
objToStrMap({yes: true, no: false})  // Map('yes'=> true, 'no'=>false)

Some precautions when using Map

const map = new Map()

map.set(NaN, 10).set(NaN, 100). //{NaN => 100}

Guess you like

Origin blog.csdn.net/kang_k/article/details/104021258