閱讀文檔幾年我經常被解釋函數簽名時常用的語法所困惑。例如:解釋API函數簽名語法
var new_array = arr.map(callback[, thisArg])
文檔列表中三個參數的回調:CurrentValue的,索引和數組,但簽名只是有這種怪異的回調[,thisArg]語法。與逗號有什麼關係?爲什麼在'回調'旁邊有數組括號?這個語法中是否有任何文檔?有這個語法的名字嗎?任何幫助,將不勝感激。
謝謝!
閱讀文檔幾年我經常被解釋函數簽名時常用的語法所困惑。例如:解釋API函數簽名語法
var new_array = arr.map(callback[, thisArg])
文檔列表中三個參數的回調:CurrentValue的,索引和數組,但簽名只是有這種怪異的回調[,thisArg]語法。與逗號有什麼關係?爲什麼在'回調'旁邊有數組括號?這個語法中是否有任何文檔?有這個語法的名字嗎?任何幫助,將不勝感激。
謝謝!
括號內的參數表示它們是可選的。
功能Array.prototype.map
期望的功能作爲第一個參數:
var new_array = arr.map(callback[, thisArg])
方括號指示secondparameter是可選的。無論是否有第二個參數,您都可以致電Array.prototype.map
。這兩個函數的調用都是有效的:
var array = [1, 2, 3, 4];
var myFunc = function (number) {
return number * 5;
};
var myFuncUsingThis = function (number) {
console.log(this);
return number;
};
var myThisArg = {
foo: 'bar'
};
console.log(array.map(myFunc));
console.log(array.map(myFuncUsingThis, myThisArg));
最後是一樣的
console.log(array.map(myFuncUsingThis.bind(myThisArg)));
因此,如果您提供給Array.prototype.map
功能使用this
對象,你可以指定該函數的this
對象通過使用第二個(可選)參數被Array.prototype.map
調用時。
currentValue
,index
和array
是完全不同的東西。當您致電Array.prototype.map
時,您無需提供。相反,Array.prototype.map
爲你提供了它們:它調用你用這三個參數給它的函數(但你不必使用全部三個參數)。
函數的第一個參數是當前正在處理的數組中元素的值,第二個參數是該元素的索引,第三個參數是數組本身。
您可以編寫一個函數,它使用了索引參數:
var array = Array(20).fill(0); // an array containing 20 zeros
var evenNumbers = array.map(function (number, index) {
// number is zero, index is the index of the element we should transform
return index * 2;
});
console.log(evenNumbers);
也許它幫助,如果你看看一個(幼稚)實現的Array.prototype.map
:
Array.prototype.map = function (callback, thisArg) {
// "this" is the array on which we work
var arr = []; // the new array that we build
var result;
for (var i = 0; i < this.length; i += 1; i++) {
result = callback.call(thisArg, this[i], i, this);
arr[i] = result;
}
return arr;
};
[JavaScript中可選參數的文檔]的可能重複(https://stackoverflow.com/questions/17132014/docu精神質換可選參數式的JavaScript) – Andreas