<script> var a = {n:1}; a.x = a = {n:2}; console.log(a.x); //undefined var b = {n:1}; b = b.x = {n:2}; console.log(b); //object{n:2} console.log(b.x); //undefined</script>三个输出是什么原理?谢谢
1 回答

Qyouu
TA贡献1786条经验 获得超11个赞
a.x = a = {n:2};
等式从右边开始计算,但是在计算之前先求得各个变量的地址。即a.x
中的a指向{n:1}
这个对象,而连等式中的a
指向{n:2}
这个对象,即运算完成后,a
指向{n:2}
,因此在连等赋值后打印a.x
是undefined
。用下面这个例子更明白点
var b = {n:1};
b = b.x = {n:2};
console.log(b); //object{n:2}
console.log(b.x); //undefined
第二个例子同样的道理,等式中间b.x中的b指向的是{n:1}这个对象,然而等式左边的b指向了{n:2}这个对象,即运算完成后,b指向{n:2},因此后来打印的b为{n:2},而b.x即为{n:2}[x],所以是undefined
添加回答
举报
0/150
提交
取消