Front-end daily exercise <type of attribute name>

topic:

var a = {
    
    };
var b = {
    
    key:'b'};
var c = {
    
    key:'c'};

a[b] = 123;
a[c] = 456;
console.log(a[b]);

What will the above code output?

The answer is: 456

Why?

Here are a few knowledge points involved:

  • Object property name type
  • The difference between a.key and a[key]
  • [object].toString() result

Object property name type

There can only be two types of attribute names of objects, namely String and Symbol. If the type of the newly added attribute is not one of the two types, then the toString() method will be called to convert it to string type

[object].toString() result

Given an object obj, the result of obj.toString() is[object,object]

image-20220614175647886

The difference between a.key and a[key]

Suppose there is an object a

let a = {
    
    key:'a'}

Executing a.key will actually get the attribute named in a key, here keyis a string, which is actually getting a['key']

And executing a[key] will look for keya variable named, soa[key] !== a[‘key’]

let a  = {
    
    key:'a'};

console.log(a.key);//'a'
console.log(a['key']);//'a'
console.log(a[key]);//error

After understanding these knowledge points, we can know the result of the code just now

image-20220614180318663

  • Since both b and c are objects, calling a[b] or a[c] will execute the toString method of the object, a[b] is equivalent to a['[object, object]'], a[c], etc. Value in a['[object,object]']

    So the above code is to reassign a['[object,object]']

    will eventually output 456

Guess you like

Origin blog.csdn.net/Laollaoaolao/article/details/125283502