JS多维数组遍历:按列提取元素生成指定长度加密词的实现
按列拼接二维数组生成加密词解决方案
看起来你需要的是把二维数组里每一列的元素依次拼接,生成对应的加密词——也就是先把所有子数组的第1个元素拼起来,再拼第2个,直到第5个(满足最大5字符的要求)。我来帮你修改代码实现这个逻辑:
基础实现(子数组长度一致的情况)
如果你的每个子数组长度都是5(和示例一样),可以用下面的代码:
var cubes = [ ['a','b','c','d','e'], ['f','g','h','i','j'], ['k','l','m','n','o'] ]; var encryptedWords = []; // 列数等于子数组的长度,这里是5 const columnCount = cubes[0].length; // 外层循环遍历每一列的位置 for (let col = 0; col < columnCount; col++) { let currentWord = ''; // 内层循环遍历每一行,取出当前列的元素拼接 for (let row = 0; row < cubes.length; row++) { currentWord += cubes[row][col]; } encryptedWords.push(currentWord); } console.log(encryptedWords); // 输出结果: ["afk", "bgl", "chm", "din", "ejo"]
进阶处理(子数组长度不一致的情况)
如果你的子数组长度可能不一样,同时要保证每个加密词最长5个字符,可以加个判断处理边界:
var cubes = [ ['a','b','c'], ['f','g','h','i'], ['k','l','m','n','o'] ]; var encryptedWords = []; // 取最长子数组的长度,但不超过5(满足加密词最大长度要求) const maxColumnCount = Math.min(Math.max(...cubes.map(arr => arr.length)), 5); for (let col = 0; col < maxColumnCount; col++) { let currentWord = ''; for (let row = 0; row < cubes.length; row++) { // 只拼接存在的元素,避免出现undefined if (cubes[row][col]) { currentWord += cubes[row][col]; } } encryptedWords.push(currentWord); } console.log(encryptedWords); // 输出结果: ["afk", "bgl", "chm", "in", "o"]
代码解释
- 核心逻辑是把循环顺序反过来:原来的代码是先遍历行再遍历列,现在改成先遍历列再遍历行,这样就能按列收集元素拼接
- 用
encryptedWords存储结果,比原来的tmp语义更明确 - 进阶版本里用
Math.min限制了最大列数为5,同时处理了子数组长度不一致的情况,避免拼接出undefined
内容的提问来源于stack exchange,提问作者ashToronto
相关产品推荐
相关产品推荐

