Notes on using Symbol
How does Symbol operate with strings
const s = Symbol('s') // Casts throw type errors console.log(s +)'/s'); // TypeError: Cannot convert a Symbol value to a string
console.log(`${s}/s') // TypeError: Cannot convert a Symbol value to a string console.log(string (s) +'/s');
console.log(s.toString() + '/s');
Copy the code
What methods related to attribute keys recognize Symbol
- The following methods recognize Symbol as the property key
- Reflect. OwnKeys () - Object. GetOwnPropertySymbols () - [] access to the operatorCopy the code
const name = Symbol('name')
const o = {
[name]: 'kobe', a: 1, b: 2 } const copy = Object.assign(Object.create(null), o) console.log(Reflect.ownKeys(o)); / / /'a'.'b', Symbol(name) ] console.log(Object.getOwnPropertySymbols(o)); // [ Symbol(name) ] console.log(o[name]); // kobe console.log(Reflect.ownKeys(copy)); / / /'a'.'b', Symbol(name) ]
Copy the code
- The following methods do not recognize Symbol as the attribute key
- Object.keys()
- Object.getOwnPropertyNames()
- for-in loop
Copy the code
const name = Symbol('name')
const o = {
[name]: 'kobe',
a: 1,
b: 2
}
for (let key ino) { console.log(key); // a b } console.log(Object.keys(o)); / / /'a'.'b'] console.log(Object.getOwnPropertyNames(o)); / / /'a'.'b' ]
Copy the code