在用 JavaScript 遍歷陣列時,常見的語法有兩種:
for (var i = 0; i < array.length; i++) {
statement;
}
for (var i in array) {
statement;
}
這兩種寫法看起來在做同一件事,但實際的循環次數往往不同。下面用一個「點擊讓方塊變紅」的小範例來說明這個差異。
<!DOCTYPE html>
<html>
<head>
<style>
#button{text-align:center;}
#outer{width:330px; height:100px; margin:10px auto;}
#outer div{float:left;width:100px;height:100px;margin:0px 5px;background:black;}
</style>
<script>
window.onload = function () {
var obutton = document.getElementsByTagName("button")[0];
var outer = document.getElementById("outer");
var outerDiv = outer.getElementsByTagName("div");
obutton.onclick = function () {
for (var p in outerDiv) outerDiv[p].style.background = "red";
};
};
</script>
</head>
<body>
<div id="button">
<button>點擊變紅色</button>
</div>
<div id="outer">
<div></div>
<div></div>
<div></div>
</div>
</body>
</html>
這段程式用了 for-in 做循環,乍看沒有問題。但在瀏覽器主控台執行時會跳出錯誤:
Uncaught TypeError: Cannot set property 'background' of undefined
把迴圈內容換成 alert(p) 就會看到答案:
for (var p in outerDiv) alert(p);
輸出依序是:
0 1 2 length item
關鍵就在這裡:getElementsByTagName 回傳的是一個 HTMLCollection,除了索引 0、1、2 之外,這個集合物件本身還帶有 length 與 item 這兩個屬性/方法。而 for-in 枚舉的是「物件的所有可列舉鍵」,它會把這些內建成員一起數進來。於是當 p 等於 "length" 時,outerDiv["length"] 是一個數字 3,數字上沒有 style,取 .background 自然是 undefined,賦值就拋錯了。
<!DOCTYPE html>
<html>
<head>
<style>
#button{text-align:center;}
#outer{width:330px; height:100px; margin:10px auto;}
#outer div{float:left;width:100px;height:100px;margin:0px 5px;background:black;}
</style>
<script>
window.onload = function () {
var obutton = document.getElementsByTagName("button")[0];
var outer = document.getElementById("outer");
var outerDiv = outer.getElementsByTagName("div");
obutton.onclick = function () {
for (var i = 0; i < outerDiv.length; i++) {
outerDiv[i].style.background = "red";
}
};
};
</script>
</head>
<body>
<div id="button">
<button>點擊變紅色</button>
</div>
<div id="outer">
<div></div>
<div></div>
<div></div>
</div>
</body>
</html>
遍歷陣列或類陣列(HTMLCollection、NodeList、arguments)請一律用 for 迴圈或 forEach,不要用 for-in。for-in 是為物件設計的,它枚舉的是鍵名稱,而且:
Array.prototype 或 NodeList.prototype 的舊套件,for-in 就會取到意料之外的鍵。若真的必須用,請加 hasOwnProperty 過濾。今天的寫法可以更簡潔:
// forEach
outerDiv.forEach(function (div) {
div.style.background = "red";
});
// 或用展開運算子轉成真陣列
[...outerDiv].forEach(div => div.style.background = "red");
順帶一提,若要一次改多個元素的樣式,加上 class 再讓 CSS 處理會比迴圈逐一設定效能更好,也更容易維護:
.is-red { background: red; }
outer.classList.add("is-red"); // 一行完成
最後,示範中的 for (var i; i < ...) 寫法(漏寫初始值 0)也是常見筆誤——var i 的值是 undefined,比較運算 undefined < 3 結果為 false,迴圈一次都不會執行。