簡體   English   中英

有沒有使用“ forEach”而不是“功能編程”的方法來解決這個問題?

[英]Is there a more “functional programming” approach to solve this without using `forEach`?

我聽說它說過,有了新的(或至少是更好的)JavaScript語言選項,我們不再需要使用forEach 我想知道這是否是倡導函數式編程的間接方式。 最近,我遇到了需要嵌套使用forEach的數組操作算法,並且想知道是否存在一種更實用的方法來解決此問題。 我可以使用reduce來重新編寫代碼,但最終比forEach解決方案更長。 就其本身而言,稍長的代碼可能並不“糟糕”,但這確實使我懷疑是否存在使用函數式編程來解決此問題的更好方法。

問題如下:重新處理數組的數組以生成所有原始元素的扁平數組,但是現在每個新元素都與其原始子數組的編號配對。 例如,將[[8,2,4],[5],[1,7]]轉換為[[8,0],[2,0],[4,0],[5,1],[1,2],[7,2]]

(為了使讀者理解對該問題的許多最初的批判性評論,該問題的原始措辭着眼於使代碼更短。我的真實意圖是詢問解決該問題的更好方法,從而導致上面的措詞問題。)

 const oldArr = [[8,2,4],[5],[1,7]]; const newArr1 = []; oldArr.forEach((subArr, subArrNum) => { subArr.forEach(elmt => {newArr1.push([elmt, subArrNum]);}); }); const newArr2 = oldArr.reduce((accum1, subArr, subArrNum) => accum1.concat( subArr.reduce((accum2, elmt) => accum2.concat([[elmt, subArrNum]]), []) ), []); console.log(JSON.stringify(newArr1)); console.log(JSON.stringify(newArr2)); // for the sake of comparing code length, here are the exact same two // solutions using only single letter variable names with each solution // compressed onto a single line: const o = oldArr; let x,y; x=[];o.forEach((s,n)=>{s.forEach(e=>{x.push([e,n]);});}); y=o.reduce((a,s,n)=>a.concat(s.reduce((b,e)=>b.concat([[e,n]]),[])),[]); console.log(JSON.stringify(x)); console.log(JSON.stringify(y)); 

在對該問題的評論中,@ Ryan提供了一個解決方案,在下面的代碼中標記為newArray1 ,而@Potter提供了一個“ babel-safe”變體,標記為newArray2 (變量名稍有更改,並刪除了括號以使兩種功能比較容易比較):

 const o = [[8,2,4],[5],[1,7]]; const newArray1 = [].concat ( ...o.map((x,i)=>x.map(y=>[y,i]))); const newArray2 = [].concat.apply([], o.map((x,i)=>x.map(y=>[y,i]))); console.log(JSON.stringify(newArray1)); console.log(JSON.stringify(newArray2)); 

我認為該解決方案的混亂程度比我原來的功能性解決方案稍微容易理解。

但是請注意,Ryan在對該問題的進一步評論中也指出了這種方法的問題。 他寫道[].concat(...x) (而且我想也是“ Babel-safe”的變體)“ ...可能會導致堆棧溢出;請嘗試[].concat(...Array(1000000)) 。理想情況下,將沿着const concat = arrs => arrs.reduce((m, n) => m.concat(n), []);的線存在一個內置const concat = arrs => arrs.reduce((m, n) => m.concat(n), []); (但可能更有效) ”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM