我有这样的3(或n)个字符串,总长度相同:
abc
将这些字符串组合在一起的最佳方式是什么:
"abc "
" xy "
" xy ---- "
" ---- "
" ---- xcv "
答案 0 :(得分:2)
使用Array#reduce
和Array#forEach
你可以做这样的事情
var a = "abc ",
b = " xy ",
c = " xy ---- ",
d = " ---- ",
e = " ---- xcv ";
var res = [
a.split(''), // split intosingle character array
b.split(''),
c.split(''),
d.split(''),
e.split('')
].reduce(function(arr, v) { // iterate and generate character array
// iterate each array element and set arr value if non space character found
v.forEach(function(v1, i) {
if (v1.trim().length)
arr[i] = v1;
})
// return updated array
return arr;
// set initial value as an array of string size and fill it with ' '(space)
}, new Array(a.length).fill(' ')).join(''); // join the result array to generate the string
console.log(res);