JS seventh languages types --symbol

Today found when browsing the web, JS type in seven languages. My heart? ? ?
Baidu, where they come from seventh! !

Well come along look at the first six JS
undefined null boolean string numver object
there is one, the new guy, symbol

When Baidu after I get the following answer:

It represents a unique value, which is the object of all non-string key collection. Symbol by Symbol value generating function. This means that the name of the object attributes can now have two types, one is the original, there's a string, and the other is the new Symbol type. Those who belong Symbol type attribute name, it is unique, and can be guaranteed not to conflict with other property name. Symbol function can take a string as parameter Symbol represent a description of examples, but even to describe the same, the value is not equal to Symbol.
On the other hand, each Symbol is unique, not repeated with other Symbol (even with the same Symbol description created), creates a Symbol just as easy to create an object.

 

let tip = Symbol("xx");
let tap= Symbol("xx");

console.log(tip== tap); // false

It is noted that: different from other types is, Symbol can not be automatically converted to a string, when an attempt to force a Symbol into a string, returns a TypeError.

> var sym = Symbol("<3");
> "your symbol is " + sym
// TypeError: can't convert symbol to string
> `your symbol is ${sym}`
// TypeError: can't convert symbol to string
  
> var sym = Symbol("<3");
> "your symbol is " + sym
// TypeError: can't convert symbol to string
> `your symbol is ${sym}`
// TypeError: can't convert symbol to string

Should avoid such a cast, you should use the String (sym) or sym.toString () to convert.
Three methods of obtaining Symbol

    1. Symbol () returns a unique Symbol each call.
    2. Symbol.for (string) returns the corresponding Symbol Symbol from the registry, the previous method is different, Symbol Symbol registry is shared. That is, if you call Symbol.for ( "cat") three times, will return the same Symbol. When a different page or different modules need to share the same page Symbol, the registry is useful.
    3. 3.Symbol.iterator return some predefined Symbol language, each has its own special purpose.

Guess you like

Origin www.cnblogs.com/JiAyInNnNn/p/11468250.html