
本文介绍如何使用原生 javascript 将字符串数组(如 ['braid', 'write', 'pence', 'schmo'])按字符位置进行“垂直拼接”,生成新数组(如 ['bwps', 'rrec', 'ainh', 'itcm', 'deeo']),适用于矩阵转置类文本处理场景。
这种变换本质上是对字符串数组执行列优先转置(column-wise transpose):将原数组视为一个不规则字符矩阵(每行是一个字符串),然后提取第 0 列所有字符、第 1 列所有字符……直至最长字符串的末尾,每列拼成一个新字符串。
核心思路分三步:
- 确定目标长度:取所有字符串长度的最大值(Math.max(...words.map(w => w.length))),即转置后新数组的元素个数;
- 构建结果数组:使用 Array.from() 创建指定长度的空数组,并为每个索引 i 映射出该“列”的字符组合;
- 逐列提取并拼接:对每个 i,遍历原数组 words,取 word[i](若越界则用空字符串 ' ' 补位),再用 .join('') 合并。
✅ 完整可运行示例:
const words = ['braid', 'write', 'pence', 'schmo'];
const result = Array.from(
{ length: Math.max(...words.map(w => w.length)) },
(_, i) => words.map(word => word[i] ?? '').join('')
);
console.log(result);
// → ['bwps', 'rrec', 'ainh', 'itcm', 'deeo']? 关键细节说明:
立即学习“Java免费学习笔记(深入)”;
- 使用 word[i] ?? ''(空值合并运算符)替代 word[i] || '' 更严谨,避免 word[i] 为 undefined 或 null 时意外被替换(尽管字符串索引越界本就返回 undefined,二者在此场景效果一致,但 ?? 语义更清晰);
- Array.from({ length: N }, mapFn) 是创建并初始化数组的高效方式,避免先 new Array(N) 再 .fill().map() 的潜在坑(如 fill() 填充引用类型时的问题);
- 若输入为空数组 [],Math.max(...[]) 会返回 -Infinity,导致 Array.from 报错;生产环境建议增加兜底逻辑:
const maxLength = words.length ? Math.max(...words.map(w => w.length)) : 0;
const result = Array.from({ length: maxLength }, (_, i) =>
words.map(w => w[i] ?? '').join('')
);? 扩展提示:该模式也适用于其他“列聚合”需求,例如统计每列字符频次、取每列最大 ASCII 字符等,只需修改映射函数内部逻辑即可。










