-2
任何人都可以解釋這個JavaScript代碼發生了什麼嗎?我不理解其中i.reduce
與[]
通過作爲初始值的部分:任何人都可以解釋在JavaScript中減少功能
function longestString(i) {
// It will be an array like (['big',[0,1,2,3,4],'tiny'])
// and the function should return the longest string in the array
// This should flatten an array of arrays
var r = i.reduce(function(a, b) {
return a.concat(b);
}, []);
// This should fetch the longest in the flattened array
return r.reduce(function (a, b)
{
return a.length > b.length ? a : b;
});
}
我儘可能清理了你的問題,但我仍然不確定你在問什麼。你問「爲什麼」'[]'通過?或者它做了什麼?或者在['Array.reduce()'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce)上尋找文檔? – Chad
它不起作用嗎?輸出有什麼問題嗎?如果沒有,Google是一個更合適的地方問[[它是如何工作的]](https://www.google.com/search?q=javascript+reduce),因爲[第一個結果](https://開發者。 mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce)對函數有詳細的描述。 – DACrosby
http://en.wikipedia.org/wiki/Fold_(higher-order_function) – godfrzero