奇妙的 JavaScript 程式碼: for (var of of of) {...}

奇妙範例

var of = ['of'];
for (var of of of) {
  console.log(of);
}

輸出結果是字串型態的 'of'

解析

把開頭的題目整理一下,先去掉眾多 of 帶來的混亂:

var arr = ['hello world'];
for (var a of arr) {
  console.log(a); // 輸出 'hello world'
  console.log(arr); // 輸出 ['hello world']
}

變形 A

let of = ['of'];
for (let of of of) {
  console.log(of);
}
// Uncaught ReferenceError: Cannot access 'of' before initialization
var of = ['of'];
for (let of of of) {
  console.log(of);
}
// Uncaught ReferenceError: Cannot access 'of' before initialization

變形 B

let of = ['of'];
for (var of of of) {
  console.info(of);
}
// Uncaught SyntaxError: Identifier 'of' has already been declared

參考文件