簡體   English   中英

如何在Javascript中將列中的字符串轉換為行

[英]How can i convert a string in a column to row in Javascript

我如何轉換這個

"ifmanwas"
"meanttos"
"tayonthe"
"groundgo"
"dwouldha"
"vegivenu"
"sroots

進入這個

javascript中的"imtgdvsfearwermayoogoanouuiontnnlvtwttddesaohghnsseoau"

我知道 array.forEach 應該工作,只是想不出它會工作

遞歸允許我們表達一個優雅的解決方案 -

 const strings = [ "ifmanwas" , "meanttos" , "tayonthe" , "groundgo" , "dwouldha" , "vegivenu" , "sroots" ] const combine = (s = "", ...more) => { if (more.length === 0) return s if (s.length === 0) return combine (...more) else return s[0] + combine (...more, s.substr(1)) } const result = combine (...strings) console.log(result) // imtgdvsfearwermayoogoanouuiontnnlvtwttddesaohghnsseoau

嘗試這個:

 const data = ["ifmanwas", "meanttos", "tayonthe", "groundgo", "dwouldha", "vegivenu", "sroots"]; const getElement = (i)=>data.map(res=>res.slice(i, i + 1)).join('') const maxElemnt =Math.max(...data.map(res=>res.length)); const result = Array.from(Array(maxElemnt).keys()).map(r=>getElement(r)).join(''); console.log(result);

使用 Ramda.js 可以輕松做到這一點。

 const strings = [ "ifmanwas", "meanttos", "tayonthe", "groundgo", "dwouldha", "vegivenu", "sroots", ] const transposeStrings = R.pipe(R.transpose, R.flatten, R.join("")) console.log(transposeStrings(strings))
 <script src="//cdn.jsdelivr.net/npm/ramda@latest/dist/ramda.min.js"></script>

 const strings = [ "ifmanwas", "meanttos", "tayonthe", "groundgo", "dwouldha", "vegivenu", "sroots", ]; var final = ""; strings.forEach(myFunction); function myFunction(item, index) { final += item; } console.log(final);

我更喜歡使用for loop來解決這個問題。

 const array = [ "ifmanwas", "meanttos", "tayonthe", "groundgo", "dwouldha", "vegivenu", "roots", ]; const newArray = []; for (let i = 0; i < array.length; i++) { for (let j = 0; j < array[i].length; j++) { if (!newArray[j]) newArray[j] = ""; newArray[j] += array[i][j]; } } const result = newArray.join(''); console.log(result); // imtgdvsfearwermayoogoanouuiontnnlvtwttddesaohghnsseoau

暫無
暫無

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

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