[英]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);
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.