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

Explanation of Symbol data type in ES

一个新手
Release: 2017-09-27 09:56:48
Original
1795 people have browsed it


Function

Declare unique variables

Two Symbols are not equal.

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

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

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

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

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

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!

Related labels:
source:php.cn
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!