let matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ]; letspiralOrder = (matrix) => { if (matrix.length == 0) return []; let result = []; let top = 0; let bottom = matrix.length - 1; let left = 0; let right = matrix[0].length - 1; while (top < bottom && left < right) { for (let i = left; i < right; i++) result.push(matrix[top][i]); for (let i = top; i < bottom; i++) result.push(matrix[i][right]); for (let i = right; i > left; i--) result.push(matrix[bottom][i]); for (let i = bottom; i > top; i--) result.push(matrix[i][left]); right--; top++; bottom--; left++; } // 剩下一行,从左到右依次添加 if (top == bottom) { for (let i = left; i <= right; i++) { result.push(matrix[top][i]); } } elseif (left == right) { for (let i = top; i <= bottom; i++) { result.push(matrix[i][left]); } } return result; }; console.log(spiralOrder(matrix));