【问题标题】:what will be the output of the java script code?javascript代码的输出是什么?
【发布时间】:2017-10-09 12:04:50
【问题描述】:
 var a = {};
 b = {x:4};
 c = {y: 2};
a[b] = 123; 
a[c] = 456;

console.log(a[b]);

我在想,输出应该是 123 但不是,我不知道..

输出结果是什么,并说明原因

【问题讨论】:

  • 你运行的结果是什么?
  • bc 都转换为 [object Object],因此它们在 a 中占据相同的键
  • 当使用括号符号a[b]b 需要是一个字符串,而不是一个对象。
  • 您在堆栈溢出上发布此问题所浪费的时间比您应该尝试在 jsfiddle/hackerrank 或任何在线代码编辑器上运行它的时间要长。
  • 它返回 456 但我不知道它是怎么来的。

标签: javascript


【解决方案1】:
The output will be 456
// It creates an empty object
var a = {};
b = {
  x: 4
}; // b become a new object
c = {
  y: 2
}; // c become a new object
/**Next line trying to create a key in object a which will look like {x:4}
which is invalid so it will look like {[object Object]} and its value will be 123**/
a[b] = 123;
/**Same operation with following line and its value will be 456.
In this case the previous[object Object] will be over written by
new one so both occupy the same key and hence 123 is overwritten 456**/
a[c] = 456;

【讨论】:

    猜你喜欢
    • 2020-03-22
    • 1970-01-01
    • 2010-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多