forEach 是遍歷數組最常用的方法,但在老舊瀏覽器(尤其 IE8 及以下)中並不存在。一個實用的做法是在內建類型的原型上擴展一個 myForEach,內部先做能力檢測,支援則直接轉調原生方法,不支援則走手寫的 for 循環。
/**
* 在內置類原型上擴展 myForEach,處理 forEach 的兼容問題
* @param callBack 回調函數,遍歷數組每一項時執行一次
* @param context 改變 callBack 內部的 this 指向
*/
Array.prototype.myForEach = function myForEach(callBack, context) {
// 未傳 context 時,this 指向 window
typeof context === "undefined" ? context = window : null;
// 原生支援,直接轉調
if ("forEach" in Array.prototype) {
this.forEach(callBack, context);
return;
}
// 降級處理:手寫循環
for (var i = 0; i < this.length; i++) {
typeof callBack === "function"
? callBack.call(context, this[i], i, this)
: null;
}
};
1. 用 call 保持與原生一致的參數簽名。原生 forEach 的會回調會收到三個參數:當前元素、當前索引、數組本身。降級分支中 callBack.call(context, this[i], i, this) 完整復刻了這一約定,因此業務代碼在兩種環境下的行為完全一致,不需要寫任何判斷。
2. context 參數讓 this 指向可控。不傳 context 時默認指向 window,與原生 forEach 在非嚴格模式下的行為一致。這個設計讓 myForEach 能勝任「遍歷時需要訪問外部對象」的場景。
3. 用 in 而非 typeof 做能力檢測。"forEach" in Array.prototype 沿原型鏈查找,比直接判斷 typeof Array.prototype.forEach === 'function' 更嚴謹——後者若屬性存在但被賦成非函數值,判斷結果會出錯。
var arr = [1, 2, 3];
arr.myForEach(function (item, index, array) {
console.log(item, index, array);
});
// 指定 this
var obj = { factor: 10 };
arr.myForEach(function (item) {
console.log(item * this.factor);
}, obj);
它復刻了 forEach 的調用方式,但沒有復刻 forEach 的全部語義。原生 forEach 有兩個行為值得注意:
第一,跳過稀疏數組中的空位。原生 forEach 只遍歷實際存在的下標,而手寫的 for 循環會把空位當作 undefined 處理。
var sparse = [1, , 3];
sparse.forEach(function (v) { console.log(v); }); // 1, 3
// myForEach 的降級分支會輸出 1, undefined, 3
若需嚴格對齊,可在循環內加一層判斷:if (i in this) { ... }。
第二,不支持提前終止。forEach 沒有 break,只能拋異常來中斷,這點原生與自研版本一致,屬於設計使然而非缺陷。若確實需要中途退出,應改用 for 循環或 Array.prototype.some / every。
直接在 Array.prototype 上加方法能全局生效、調用簡潔,但也有風險:for...in 會枚舉到它,可能讓依賴 for...in 遍歷數組的第三方代碼出錯;若未來標準新增同名方法,也會產生衝突。
更穩妥的替代方案有兩種:
utils.myForEach(arr, fn),不污染原型。如果是新項目且能使用轉譯工具(Babel 等),配備 core-js 這類 polyfill 方案是最省心的選擇——不必自己判斷兼容性,也不必擔心語義偏差。