之前我覺得:node
var x = y = 100
複製代碼
就是連續賦值。測試
實際上,上邊的語句中, var x 只是聲明一個 x ,而後用 y = 100 的結果值去初始化 x 。spa
那什麼是連續賦值呢?舉個🌰:code
var a = {n:1},
// 這纔是連續賦值
a.x = a = {n:2};
複製代碼
可是:console
console.log(a.x); // --> undefined
複製代碼
爲何呢?class
緣由是:a 被從新賦值爲 {n:2} 後, a 的引用變成了全新的,而 js 遵循從左向右的執行原則,a.x 拿到的是老的 a 的屬性引用,console.log(a.x) 中的 a 是新的 a ,因此 undefined 。object
如何證實:引用
var a = {n:1}, ref = a; // ref暫存了「原始的a」
a.x = a = {n:2};
console.log(a.x); // undefined
console.log(ref.x); // object {n:2}
console.log(ref.n); // 1
複製代碼
因而咱們能夠利用連續賦值實現一個鏈表:鏈表
var i = 10, root = {index: "NONE"}, node = root;// 建立鏈表
while (i > 0) {
node.next = node = new Object; node.index = i--; // 這裏能夠開始給新node添加成員
node.name = `name ${i + 1}`
}
// 測試
node = root;
while (node = node.next) { console.log(node);}
複製代碼
補充:關於 . 運算:next
若是點運算在後續運算中被做爲 lhs,例如 node.next = ...,那麼它就是做爲「引用」來使用,這樣就能夠訪問到x
這個屬性,並置值;若是它在後續運算中被做爲 rhs,例如 console.log(node.next),那麼它就會被 GetValue() 取值(並做爲值來使用)。
點運算總體被做爲「一個操做數」,它的用法與它被使用的位置是有關的。可是「獲得它(亦便是對a.x這個表達式求 Result )」的過程並無什麼不一樣。