Basic knowledge of js-object

var a = {};
var b = {key: "b"};
var c = {key: "c"};
var d = [3,5,6];
a[b] = 123;
a[c] = 345;
a[d] = 333;
console.log(a[b]);  // 345
console.log(a[c]);  // 345
console.log(a[d]);  // 333

Why do both a [b] and a [c] output 345? what is the principle?

Dec.20,2021

you just need to add the console.log (a) output to your above code to understand.

clipboard.png

that is, the whole object becomes a key
even if console.log (a [{}]), the output is 345

.

if you want normal output, just put quotation marks when assigning values. A ['b'] = 123


the key value of an object can be a string or a symbol value (Symbol),. If the current key value is an object, the key value is converted to a string through toString, so the above three results can be seen as follows:

a[b] = a['[object Object]']
a[c] = a['[object Object]']
a[d] = a['3,5,6']

so the value of a [b] will be the same as the value of a [c] .

Menu