JavaScript ES(6-11) basic syntax series

Posted by leon77 on Fri, 24 Dec 2021 01:03:31 +0100

New data type symbol

S6 introduces a new raw data type Symbol, which represents a unique value.

The Symbol value is generated by the Symbol function. That is to say, there are two types of attribute names of objects. One is the original string, and the other is the new Symbol type. All attribute names that belong to Symbol type are unique, which can ensure that they will not conflict with other attribute names. Therefore, Symbol is very suitable for identifier.

Symbol has static properties and methods on the prototype, but it lacks a constructor, so new Symbol() cannot be used, and an error will be reported.

Because the generated Symbol is a value of the original type, not an object, properties cannot be added.

Each Symbol value is not equal, which means that the Symbol value can be used as an identifier for the attribute name of the object, so as to ensure that there will be no attributes with the same name. This is very useful when an object is composed of multiple modules to prevent a key from being accidentally rewritten or overwritten. When Symbol value is used as object property name, dot operator cannot be used. Inside an object, when defining a property with a Symbol value, the Symbol value must be placed in square brackets.

//Symbol is unique
let s1 = Symbol('abc')
let s2 = Symbol('abc')
s1 === s2 // false
Symbol Parameters of
let s1 = Symbol('abc');
let s2 = Symbol('efg');
s1.toString(); // "Symbol(abc)"
s2.toString(); // "Symbol(efg)";

Use symbol and symbol For defines different types of symbol data

var sym1 = symbol("foo")
var sym2 = symbol("foo")
console.log(sym1===sym2) //false
var sym3 = symbol.for("foo")
var sym4 = symbol.for("foo")
console.log(sym3===sym4) //true

Symbol () will recreate a symbol when defining a symbol data type;

symbol.for() does not create a symbol every time, but goes to the global to find out whether the symbol has been created. If it has been created, the same symbol data will be used.

Get the description of the symbol

symbol. Both for () and symbol() can use descripton to access the description content.

symbol.for() and symbol() use keyFor() to access the description content, symbol For () can be accessed, and symbol() is undefind

 |

Find whether the symbol has been registered globally

Application scenario of symbol

  • The same property name may appear in the object

var stu1 = Symbol("Li Si")
var stu2 = Symbol("Li Si")
var students = {
​
[stu1]:{name:stu1.description,score:100},
[stu2]:{score:90}
​
}
console.log(students[stu1].name)
  • When attribute names need to be protected in class

The attribute name of symbol type cannot be obtained by using for of in.

Use object Getownpropertysymbols (sym) can only get the property name of symbol type.

Use reflect Ownkeys (sym) can get the common attribute name and the attribute name of symbol type.

  • Eliminate magic string

New data structure set

Similar to an array, but member values are unique.

The Set function can accept an array or an array whose return value is an array (or other data structures with iterable interface, such as class array node collection) as parameters for initialization.

set's common API supports chain operation;

  • set.add(val) append to the end

  • set.delete(val) deletes a value

  • set.clear() clear data

  • s.has(val) determines whether a value in set returns a Boolean value

  • s.size determines how many values are in the set

How to traverse set data

  • You can use foreach (E = > {});

  • for of for in for;

  • You can use keys() to get keys, values() to get values, and entries() to get key value pairs. The set data structure key value pairs are the same.

Usage scenario

  • Array de duplication

// Array de duplication
let arr = [1,2,3,4,4,6,3]
let s = new Set(arr)
console.log(s)
  • Merge de duplication

// Merge de duplication
var arr1 = [3,3,3,3,5,4]
console.log([...new Set([...arr,...arr1])]);
  • intersection

// intersection
var s1 = new Set(arr)
var s2 = new Set(arr1)
var res = new Set(arr.filter(e=>s2.has(e)))
console.log(res);
  • Union

// Union
var s1 = new Set(arr)
var s2 = new Set(arr1)
var res = new Set([...arr,...arr1])
console.log([...res]);
  • Difference set

let arr1 = [1,2,3,5,6]
let arr2 = [2,3,6,7]
let s1 = new Set(arr1)
let s2 = new Set(arr2)
let result1 = new Set(arr1.filter(item=>!s2.has(item)))
let result2 = new Set(arr2.filter(item=>!s1.has(item)))
let resArr = [...result1,...result2]
console.log(arr2)
  • Convert set data to a real array

Using array From () or extension operator.

weakSet

weakSet() can only be used to save objects. Is a weak reference.

Application scenario

You can use a weakSet by temporarily using an object to store objects.

Difference between weakSet() and set data

  • weakSet can only store objects, and set can store different types of data.

  • set can be iterated, but weakSet cannot.

  • weakSet() is a weak reference and cannot be considered by the garbage collection mechanism.

New data structure map

Map is also a key value pair, similar to an object, but the key value of map data is not limited to strings, and various data types can be used as keys.

map common API s

let map1 = new Map()
let obj = {
	a:"zxl"
}
map1.set(obj,"This is an object")// set key value
map1.get(obj)// Get value
map1.delete(obj)// Delete obj
map1.has(obj) // Judge whether map1 contains obj attribute
map1.size //Number of attributes in map1

You can also add attributes to map data by directly passing parameters

let map = new Map([['name','imooc'],['age',5]])
console.log(map) // name=>'imooc',age=>5
console.log(map.size) // 2
console.log(map.has('name')) // true
console.log(map.get('age')) // 5
map.set('name','zs')
console.log(map)// name=>'zs',age=>5

 

Traverse map data

  • forEach((val,key)=>{console.log(val.key)})

                           |

Parameters are values and key names

  • for of

for(let [key,val] of map){
	console.log(key,val)
}
  • map.keys()

for(let key of map.keys()){
	console.log(key)
}
  • map.values()

for(let val of map.values()){
	console.log(val)
}
  • map.entries()

for(let [key,val] of map.entries()){
	console.log(key,val)
}

Application scenario

It is almost consistent with the application scenario of Object. Moreover, the map data structure has more performance advantages for frequent addition, deletion, modification and query operations.

weakMap()

The key name of the weakMap data structure only supports reference types and is also a weak reference.

weakMap does not support traversal, clear(), keys(), values(), entries(), has() size

Topics: Javascript Front-end ElasticSearch