本文實(shí)例講述了JavaScript中的連續(xù)賦值問(wèn)題。分享給大家供大家參考,具體如下:
JavaScript中的連續(xù)賦值:
<script>var a = {n: 1}var b = a;a.x = a = {n: 2}console.log(a.x);//undefinedconsole.log(b.x)//Object {n: 2}</script>Javascript中賦值運(yùn)算符“=”的優(yōu)先級(jí)是除了“,”以外最低的,并且是從右向左結(jié)合的。
Javascript中運(yùn)算的順序是從左向右的。
a.x = a = {n: 2}可以看做a.x =(a = {n: 2}) ,先運(yùn)算a.x,在a中添加x屬性,結(jié)果為null,在計(jì)算表達(dá)式(a = {n: 2}),最后進(jìn)行賦值運(yùn)算。
修改程序:
<script>var a = {n: 1}var b = a;a = a.x = {n: 2}console.log(a.x);//undefinedconsole.log(b.x)//Object {n: 2}</script><script>var a = {x:{xx:1},y:2,z:3};var b = a.x; //{xx:1}var c = a;a.w = a.x.xx = a.y = a = {x:10,y:20};console.log(a);console.log(b);console.log(c);</script>運(yùn)行結(jié)果:
a : {x: 10, y: 20}
b : {xx : {x: 10, y: 20}}
c :?{x:{xx:{x:10,y:20}},y:{x:10,y:20},z:3,w:{x:10,y:20}}
<script>console.log(c.x.xx.x);//10console.log(c.y.x);//10console.log(c.w.x);//10</script>
希望本文所述對(duì)大家JavaScript程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答