本文實例講述了JavaScript中的連續賦值問題。分享給大家供大家參考,具體如下:
JavaScript中的連續賦值:
<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中賦值運算符“=”的優先級是除了“,”以外最低的,并且是從右向左結合的。
Javascript中運算的順序是從左向右的。
a.x = a = {n: 2}
可以看做a.x =(a = {n: 2})
,先運算a.x,在a中添加x屬性,結果為null,在計算表達式(a = {n: 2})
,最后進行賦值運算。
修改程序:
<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>
運行結果:
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>
希望本文所述對大家JavaScript程序設計有所幫助。
新聞熱點
疑難解答