Home > Article > Web Front-end > Explanation of Symbol data type in ES
Function
Two Symbols are not equal.
let a1 = Symbol(); //不用newlet a2 = Symbol(); console.log(a1===a2); //false
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
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
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})
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!