JavaScript 的逗號操作符
除了分號之外,逗號允許你在同一個地方放多個語句。 例如:
for(var i=0, j=0; i<5; i++, j++, j++){
console.log("i:"+i+", j:"+j);
}
輸出:
i:0, j:0
i:1, j:2
i:2, j:4
i:3, j:6
i:4, j:8
當放置一個表達式時,它由左到右計算每個表達式,並回傳最右邊的表達式。
例如:
function a(){console.log('a'); return 'a';}
function b(){console.log('b'); return 'b';}
function c(){console.log('c'); return 'c';}
var x = (a(), b(), c());
console.log(x); // 輸出「c」
輸出:
"a"
"b"
"c"
"c"
- 注意:逗號(
,
)操作符在 JavaScript 所有 的操作符是最低的優先順序,所以如果沒有括號表達式將變成:(x = a()), b(), c();
。
Playground

MEET THE NEW JSTIPS BOOK
You no longer need 10+ years of experience to get your dream job.
Use the 100 answers in this short book to boost your confidence and skills to ace the interviews at your favorite companies like Twitter, Google and Netflix.
GET THE BOOK NOW

MEET THE NEW JSTIPS BOOK
The book to ace the JavaScript Interview.
A short book with 100 answers designed to boost your knowledge and help you ace the technical interview within a few days.
GET THE BOOK NOW