Home > Web Front-end > JS Tutorial > body text

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

不言
Release: 2018-10-25 15:31:41
forward
2738 people have browsed it

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
}
Copy after login

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"}
}
Copy after login

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"
    });
}
Copy after login

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!

Related labels:
source:segmentfault.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template