試圖理解這一點:
const _ = {};
_.map = function(list, callback){
var storage = [];
for(let i=0; i<list.length; i ){
storage.push(callback(list[i], i, list));
}
return storage;
}
_.map([1,2,3], function(val){return val 1;})
為什么回呼需要 3 個引數,而我們顯然只需要一個引數?
_.map = function(list, callback){
var storage = [];
for(let i=0; i<list.length; i ){
storage.push(callback(list[i])); //****** This works too!
}
return storage;
}
_.map([1,2,3], function(val){return val 1;})
背景:做一門關于前端大師的課程,他們像第一個版本一樣實作它。
uj5u.com熱心網友回復:
Array#map 方法最多可以有 3 個引數用于其回呼。這里提到https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
map((element) => { ... })
map((element, index) => { ... })
map((element, index, array) => { ... })
由于您沒有使用其他兩個引數,index, array因此它們將是未定義的。
為兩個宣告運行以下代碼以更好地理解。
_.map([1,2,3], function(val,index,arr){
console.log(val)
console.log(index)
console.log(arr)
})
uj5u.com熱心網友回復:
這是因為如果您查看Array.prototype.map的當前定義,回呼函式最多可以接收三個引數,如下所示。
map(function callbackFn(element) { ... })
map(function callbackFn(element, index) { ... })
map(function callbackFn(element, index, array){ ... })
map(function callbackFn(element, index, array) { ... }, thisArg)
除了呼叫 map 函式的陣列上給定索引處的專案外,您還可以接收索引和陣列本身。
回呼函式
為 arr 的每個元素呼叫的函式。每次執行 callbackFn 時,回傳值都會添加到 newArray。
callbackFn 函式接受以下引數:
元素
The current element being processed in the array.索引可選
The index of the current element being processed in the array.陣列可選
The array map was called upon.thisArg可選
執行 callbackFn 時用作 this 的值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/339666.html
標籤:javascript
上一篇:創建后事件發射器無法正常作業
