[英]concatenate using Underscore reduce?
有人可以幫我解決這個問題嗎? 我試圖
使用(下划線)_.reduce連接數組中的所有字符串。
輸入:
['x','y','z']
輸出:
'xyz'
這是我的開始方式:
_.reduce(['x','y','z'], function(current, end) {
return...
});
您可以在這里簡單地使用Array.prototype.join
。 在這種情況下,它比reduce
效率更高。
console.log(['x','y','z'].join(""));
// xyz
但是,如果您想使用_.reduce
,您可以這樣做
_.reduce(['x', 'y', 'z'], function(accumulator, currentItem) {
return accumulator + currentItem;
});
// xyz
_.reduce
只是在支持Array.prototype.reduce
的環境中的包裝。 您可以從此答案中詳細了解reduce
如何處理輸入。
這是一個簡短的解釋。
由於沒有傳遞給_.reduce
初始值,因此集合中的第一個值將用作累加器值,並使用累加器值和第二個值調用該函數。 因此,該函數稱為
accumulator : 'x'
currentItem : 'y'
-----------------
accumulator : 'xy' (because returned value will be passed again as accumulator)
在下一個通話中
accumulator : 'xy'
currentItem : 'z'
-----------------
accumulator : 'xyz' (since no elements left, accumulator will be returned)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.