类别:js / 日期:2023-05-08 / 浏览:481 / 评论:0
// example 1
var a = {},
b = "123",
c = 123;
a[b] = "b";
a[c] = "c";
console.log(a[b]);
// ---------------------
// example 2var a={}, b=Symbol('123'), c=Symbol('123');
a[b] = "b";
a[c] = "c";
console.log(a[b]);
// ---------------------
// example 3var a={}, b={key:'123'}, c={key:'456'};
a[b] = "b";
a[c] = "c";
console.log(a[b]);
答:
1.对象的键名只能是字符串和 Symbol 类型。
2.其他类型的键名会被转换成字符串类型。
3.对象转字符串默认会调用 toString 方法。
// example 1
var a={}, b='123', c=123;a[b]='b';
// c 的键名会被转换成字符串'123',这里会把 b 覆盖掉。a[c]='c';
// 输出 cconsole.log(a[b]);
// example 2var a={}, b=Symbol('123'), c=Symbol('123');
// b 是 Symbol 类型,不需要转换。a[b]='b';
// c 是 Symbol 类型,不需要转换。任何一个 Symbol 类型的值都是不相等的,所以不会覆盖掉 b。
a[c]='c';
// 输出 bconsole.log(a[b]);
// example 3var a={}, b={key:'123'}, c={key:'456'};
// b 不是字符串也不是 Symbol 类型,需要转换成字符串。
// 对象类型会调用 toString 方法转换成字符串 [object Object]。a[b]='b';
// c 不是字符串也不是 Symbol 类型,需要转换成字符串。
// 对象类型会调用 toString 方法转换成字符串 [object Object]。这里会把b 覆盖掉。
a[c]='c';
// 输出 cconsole.log(a[b]);

发表评论 / 取消回复