【每日一題】用for實(shí)現(xiàn)forEach

人生苦短,總需要一點(diǎn)儀式感。比如學(xué)前端~
forEach
語(yǔ)法:
arr.forEach(callback(currentValue [, index [, array]])[, thisArg])
// 完整的參數(shù)使用,比如:
arr.forEach(function (currentValue, index, array) {
console.log(this, currentValue, index, array)
}, thisArg)
參數(shù)
callback
為數(shù)組中每個(gè)元素執(zhí)行的函數(shù),該函數(shù)接收一至三個(gè)參數(shù):
currentValue
數(shù)組中正在處理的當(dāng)前元素。
index 可選
數(shù)組中正在處理的當(dāng)前元素的索引。
array 可選
forEach() 方法正在操作的數(shù)組。
thisArg 可選
可選參數(shù)。當(dāng)執(zhí)行回調(diào)函數(shù) callback 時(shí),用作 this 的值。
若不傳該參數(shù),非嚴(yán)格模式下,this默認(rèn)指向window;非非嚴(yán)格模式下,this默認(rèn)指向undefined。
實(shí)現(xiàn)
Array.prototype.myForEach = function (fn, context = undefined) { // 將myForEach函數(shù)掛載到Array原型上
if (typeof fn !== "function") { // 判斷,調(diào)用myForEach時(shí)傳入的是否是函數(shù)
throw new TypeError(fn + "is not a function"); // 不是函數(shù)則拋出類型錯(cuò)誤
}
for (let i = 0; i < this.length; i++) { // this指向調(diào)用myForEach的數(shù)組,使用for循環(huán)遍歷這個(gè)目標(biāo)數(shù)組
fn.call(context || Window, this[i], i, this); // 使用call調(diào)用該回調(diào)函數(shù),為了是修改回調(diào)函數(shù)內(nèi)部的this。
}
};
測(cè)試:非嚴(yán)格模式下,this默認(rèn)指向window
注意:測(cè)試this,callback千萬(wàn)記得別用錯(cuò)成了箭頭函數(shù)。否則測(cè)不對(duì)
var arr = [3, 4, 5, 6];
arr.myForEach(function (item, index) {
console.log(this, item, index, "==普通使用==");
});

const thisArg = {name: 'this指向本對(duì)象'}
arr.myForEach(function(item, index) { // 注意這里別用箭頭函數(shù),不然函數(shù)內(nèi)部this永遠(yuǎn)指向上個(gè)非箭頭作用域的this
console.log(this, item, index, '==this指向==')
}, thisArg)

while 版本
代碼:
Array.prototype.myForEach = function (callback, thisArg) {
if (this == null) {
throw new TypeError("this is null or not defined");
}
if (typeof callback !== "function") {
throw new TypeError(callback + "is not a function");
}
let obj = Object(this),
len = obj.length;
idx = 0;
// 得到目標(biāo)數(shù)組的長(zhǎng)度,進(jìn)行while循環(huán)
while (idx < len) {
let value;
if (idx in obj) {
value = obj[idx];
callback.call(thisArg, value, idx, obj);
}
idx++;
}
};
var a = [3, 4, 5, 6];
a.myForEach((item, index) => {
console.log(item, index, "====");
});
測(cè)試:


讓我們一起攜手同走前端路!
關(guān)注公眾號(hào)回復(fù)【加群】即可

● 工作中常見頁(yè)面布局的n種實(shí)現(xiàn)方法
● 三欄響應(yīng)式布局(左右固寬中間自適應(yīng))的5種方法
● 兩欄自適應(yīng)布局的n種實(shí)現(xiàn)方法匯總
評(píng)論
圖片
表情
