最近工作中遇到的情况,用 js 将二维数组旋转展开为一维数组,记录一下:
函数如下:function roll_out(array) {
const outputArr = []; const len_i = array.length; const len_j = array[0].length; let i_init = 0; let j_init = 0; let i_end = array.length - 1; let j_end = array[0].length -1; let count = 0; const all = len_i * len_j; let direction = 'right_left'; while (count < all) { switch(direction) { case 'left_right':{ for(var i = i_init, j = j_init; j <= j_end; j++, count++) { outputArr.push(array[i][j]) } direction = 'top_bottom'; i_init++; break; } case 'top_bottom':{ for(var i = i_init, j = j_end; i <= i_end; i++, count++) { outputArr.push(array[i][j]) } direction = 'right_left'; j_end--; break; } case 'right_left':{ for(var i = i_end, j = j_end; j >= j_init; j--, count++) { outputArr.push(array[i][j]) } direction = 'bottom_top'; i_end--; break; } case 'bottom_top':{ for(var j = j_init, i = i_end; i >= i_init; i--, count++) { outputArr.push(array[i][j]) } direction = 'left_right'; j_init++; break; } } } console.log(outputArr)
}
主要就是方向转变的处理,改变 direction 的初始值可以选择从哪一个角开始旋转展开。
测试用例:
// 用例1 const array = [ [1,2,3,4], [12,13,14,5], [11,16,15,6], [10,9,8,7] ] // 输出 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] // 用例2 const array_len2 = [ [1,2,3,4,5,6,7,8], [18,19,20,21,22,23,24,9], [17,16,15,14,13,12,11,10] ] // 输出 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]