Home  >  Article  >  Web Front-end  >  Explanation of Symbol data type in ES

Explanation of Symbol data type in ES

一个新手
一个新手Original
2017-09-27 09:56:481801browse


Function

Declare unique variables

Two Symbols are not equal.

let a1 = Symbol();  //不用newlet a2 = Symbol();
console.log(a1===a2); //false

Prevent key value conflicts

let a1=Symbol.for('abc');let obj={
        [a1]:'123',        'abc':345,        'c':456};
console.log('obj',obj);  // {abc: 345, c: 456, Symbol(abc): "123"}

[a1] is the above Symbol, its key value is 'abc',

There is also a key value below which is 'abc' ', but there is no conflict.

Method

Symbol.for() Find key value

This method will search for key value globally,

If If is present, will return the value ;

If does not have , the key value will be generated.

let a3=Symbol.for('a3'); //声明keylet a4=Symbol.for('a3'); //找到变量a3对应的key值
console.log(a3===a4);    //a3 === a3

Object.getOwnPropertySymbols() Get value

It can only get the value of Symbol(), cannot get the value of ordinary properties
Return Value:

Array

Instance

let s5 = Symbol('s5');let s6 = Symbol('s6');let a = {
    [s5]: 'rs5',
    [s6]: 'rs6'}Object.getOwnPropertySymbols(a).forEach(function(item){
    console.log(a[item]);  // rs5  rs6})

Reflect.ownKeys() Get key and value

can be obtained Symbol() and non-Symbol key and value values
Return value: Array Example

let s5 = Symbol('s5');let s6 = Symbol('s6');let a = {
    [s5]: 'rs5',
    [s6]: 'rs6'}

Reflect.ownKeys(a).forEach(function(item){
    console.log(item,a[item]); // Symbol(s5) "rs5"  Symbol(s6) "rs6"})

The above is the detailed content of Explanation of Symbol data type in ES. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn