SOURCE

let input = [
    [1,2,3,4,5],
    [14,15,16,17,6],
    [13,20,19,18,7],
    [12,11,10,9,8],
]

function output (input){
    let left = 0;
    let top = 0;
    let bottom = input.length-1;
    let right = input[0].length-1;
    if(!bottom || !right) return [];
    let direction = 'right';
    let res = [];
    while(left <= right && top<=bottom){
        if(direction == 'right'){
            for(let i=left;i<=right;i++){
                res.push(input[top][i]);
            }
            top++;
            direction = "bottom";
        }
        if(direction == 'bottom'){
            for(let i=top;i<=bottom;i++){
                res.push(input[i][right]);
            }
            right--;
            direction = "left";
        }
        if(direction == 'left'){
            for(let i=right;i>=left;i--){
                res.push(input[bottom][i]);
            }
            bottom--;
            direction = "top";
        }
        if(direction == 'top'){
            for(let i=bottom;i>=top;i--){
                res.push(input[i][left]);
            }
            left++;
            direction = "right";
        }
    }
    return res;
}

console.log(output(input))
console 命令行工具 X clear

                    
>
console