Home >Web Front-end >JS Tutorial >Detailed explanation of the usage of ES6 Symbol (with code)

Detailed explanation of the usage of ES6 Symbol (with code)

不言
不言forward
2018-10-25 15:31:412740browse

This article brings you a detailed explanation of the usage of ES6 Symbol (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. Symbol is a new data type in ES6, which provides unique values ​​

{
    // 声明,Symbol声明的变量是唯一的
    let a1 = Symbol();
    let a2 = Symbol();
    console.log(a1 === a2); // false
    // Symbol.for()接收一个参数,作为key值
    // 使用for方法时,会检查这个key值在全局是否注册
    // 如果注册过就返回这个值,否则调用Symbol生成新的独一无二的值
    let a3 = Symbol.for('a3');
    let a4 = Symbol.for('a3');
    console.log(a3 === a4); // true
}

2. Declare Symbol type attributes in the object

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

3.Symbol Traverse

{
    let a1 = Symbol.for('abc');
    let obj = {
        [a1]: '123',
        'abc': 345,
        'df': 456,
    };
    // let of(或者for in)循环拿不到 以Symbol作为属性的值
    for (let key of Object.keys(obj)) {
        console.log(key); // abc  df
    }

    // 只拿到以Symbol作为属性的值,getOwnPropertySymbols返回一个数组
    Object.getOwnPropertySymbols(obj).forEach(function (item) {
        console.log(obj[item]); // 123
    });

    // 对象全部属性和值都拿到,包括Symbol。Reflect.ownKeys返回一个数组
    Reflect.ownKeys(obj).forEach(function (item) {
        console.log(item, obj[item]); // abc 345  df 456  Symbol(abc) "123"
    });
}

The above is the detailed content of Detailed explanation of the usage of ES6 Symbol (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete