-
Notifications
You must be signed in to change notification settings - Fork 3.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
第 76 题:输出以下代码运行结果 #125
Comments
这题考察的是对象的键名的转换。
// example 1
var a={}, b='123', c=123;
a[b]='b';
// c 的键名会被转换成字符串'123',这里会把 b 覆盖掉。
a[c]='c';
// 输出 c
console.log(a[b]); // example 2
var a={}, b=Symbol('123'), c=Symbol('123');
// b 是 Symbol 类型,不需要转换。
a[b]='b';
// c 是 Symbol 类型,不需要转换。任何一个 Symbol 类型的值都是不相等的,所以不会覆盖掉 b。
a[c]='c';
// 输出 b
console.log(a[b]); // example 3
var a={}, b={key:'123'}, c={key:'456'};
// b 不是字符串也不是 Symbol 类型,需要转换成字符串。
// 对象类型会调用 toString 方法转换成字符串 [object Object]。
a[b]='b';
// c 不是字符串也不是 Symbol 类型,需要转换成字符串。
// 对象类型会调用 toString 方法转换成字符串 [object Object]。这里会把 b 覆盖掉。
a[c]='c';
// 输出 c
console.log(a[b]); |
Got it! |
牛皮~ 看起来又是不会的知识 |
我是这样的,看完解析,才恍然觉得我好像以前记过这个啊!! |
我是知道了这个题考察的 对象 键名转换,我知道键名是string,但是第三个我想成了 stringify ,toString就比较容易理解了 |
前面说的很清楚了,除了Symbol,如果想要不被覆盖 可以使用ES6提供的Map var a=new Map(), b='123', c=123;
a.set(b,'b');
a.set(c,'c');
a.get(b); // 'b'
a.get(c); // 'c' |
喜欢这种 看着简单却做不对的题目TT |
对象类型应该是调用 |
javascript 普通对象的key都是字符串。 所以: 1,a[c]会先将c转换为字符串,然后再赋值。 |
// example 1
var a={}, b='123', c=123;
a[b]='b';
a[c]='c';
console.log(a[b]);
---------------------
// example 2
var a={}, b=Symbol('123'), c=Symbol('123');
a[b]='b';
a[c]='c';
console.log(a[b]);
---------------------
// example 3
var a={}, b={key:'123'}, c={key:'456'};
a[b]='b';
a[c]='c';
console.log(a[b]); |
看完流下了没有技术的泪 |
输出以下代码运行结果
|
再加一题// example 4 |
你这代码书写有问题,少了逗号啊!function也会调用toString方法,所以结果是b |
'b' 同名key 被后面的赋值覆盖 |
讲得很好,补充一下链接:https://tc39.es/ecma262/multipage/abstract-operations.html#sec-topropertykey |
// example 1
var a={}, b='123', c=123;
a[b]='b';
a[c]='c';
console.log(a[b]);
// example 2
var a={}, b=Symbol('123'), c=Symbol('123');
a[b]='b';
a[c]='c';
console.log(a[b]);
// example 3
var a={}, b={key:'123'}, c={key:'456'};
a[b]='b';
a[c]='c';
console.log(a[b]);
The text was updated successfully, but these errors were encountered: