How to understand that attributes of the same name will not appear in Symbol?
this sentence: since each Symbol value is not equal, this means that the Symbol value can be used as an identifier for the property name of the object, which ensures that an attribute with the same name will not appear.
uses Symbol:
let b = {
str: "hello"
}
The
b.str attribute will be overwritten if it has the same name, and the a [sym] attribute will also be overwritten when they have the same name attribute. So: Symbol guarantees that there will be no attributes of the same name.
since your first example is incomplete, I will only analyze your problem from the context.
this sentence: since each Symbol value is not equal, this means that the Symbol value can be used as an identifier for the property name of the object, which ensures that an attribute with the same name will not appear.
I don't know where you saw it, so I looked for another description (from MDN).
each symbol value returned from Symbol () is unique. A symbol value can be used as an identifier for an object property; this is the only purpose of the data type. See glossary entry for Symbol for further analysis. see
the number of words in the two sentences is about the same, but the description is completely different. What MDN means is that the return value is unique, it is the return value. That is, if you keep it unique, you need to call Symbol ()
.
Let's demonstrate your first example:
let sym = Symbol();
let a = {
[sym]: 'Hello'
}
console.log(a) //{ [Symbol()]: 'Hello' }
console.log(a[Symbol()]) //undefined
a[Symbol()]=123
console.log(a) //{ [Symbol()]: 'Hello', [Symbol()]: 123 }
console.log(a[sym]) //Hello
the last line is not the returned value, but the existing reference, which is the only one in memory.
console.log(sym == sym) //true
console.log(Symbol()==Symbol())//false
let json = {}
for (let index = 0; index < 11; indexPP) {
let ss = Symbol()
json[ss] = 'ssss'+index
}
console.log(json[Object.getOwnPropertySymbols(json)[3]]) // ssss3
Symbol("foo") === Symbol("foo"); // false
for example, you add a Symbol ('toString')
method and give it to others. Others have also added a Symbol ('toString')
method, which does not conflict with each other.
let a = {};
let key1 = Symbol('toString')
a[key1] = 'Hello1'
console.log(a)
let key2 = Symbol('toString')
a[key2] = 'Hello2'
console.log(a)