The difference between obj['x'] and obj[x]

Object data type:
the type of attribute name
consisting of zero to multiple sets of key-value pairs (attribute name and attribute value
) Type value, can communicate with strings during processing]

 However, the attribute name must not be a reference data type. If the reference type is set, it will be converted to a string at the end.

 

example

let sy = Symbol('AA');
let x = {
 0: 0
};
let obj = {
 0: 12,
 true: 'xxx',
 null: 20
};
obj[sy] = '珠峰';
obj[x] = 100; //=> obj['[object Object]']=100 会把对象变为字符串作为属性名

for (let key in obj) {
// FOR IN遍历中获取的属性名都会变为字符串
// 并且无法迭代到属性名是SYMBOL类型的属性
console.log(key, typeof key);
}

let x = 20;
let obj = {
 x: 100,
 20:10
};
// 属性名肯定得是一个值
// obj[x] 把x变量存储的值当做属性名, 获取对象的属性值 => obj[20] => undefined
// 如果有20:10这一项obj[x] => 10
// obj['x'] == obj.x 获取属性名为x的属性值 =>100 <=> obj.x 属性名为x

Guess you like

Origin blog.csdn.net/weixin_48927323/article/details/128005213