简体   繁体   English

如何在Javascript中将列中的字符串转换为行

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

How do i convert this我如何转换这个

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

into this进入这个

"imtgdvsfearwermayoogoanouuiontnnlvtwttddesaohghnsseoau" in javascript javascript中的"imtgdvsfearwermayoogoanouuiontnnlvtwttddesaohghnsseoau"

I know array.forEach should work, Just can not figure out it will work我知道 array.forEach 应该工作,只是想不出它会工作

Recursion allows us to express an elegant solution -递归允许我们表达一个优雅的解决方案 -

 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

Try this:尝试这个:

 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);

Using Ramda.js makes this easy to do.使用 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);

I prefer to use for loop to approach this question.我更喜欢使用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