• 环绕式遍历数组

    类型参数

    • T extends any[][]

    参数

    • arr: T

      需要遍历的数组

    • callbackFn: ((value: T extends R[][]
          ? R
          : unknown, indexes: [col: number, row: number], array: T) => any)

      回调函数

        • (value, indexes, array): any
        • 参数

          • value: T extends R[][]
                ? R
                : unknown
          • indexes: [col: number, row: number]
          • array: T

          返回 any

    • options: {
          startIndexes?: [col: number, row: number];
          startDirect?:
              | "left"
              | "top"
              | "bottom"
              | "right";
          reverse?: boolean;
      } = {}
      • 可选startIndexes?: [col: number, row: number]

        开始时的index,默认[0, 0]

      • 可选startDirect?:
            | "left"
            | "top"
            | "bottom"
            | "right"

        开始时的方向,默认向右('right'),reverse为true时向左('left')

      • 可选reverse?: boolean

        是否逆时针遍历;默认为false,顺时针遍历

    返回 void

    const arr = [
    [1, 2, 3, 4, 5],
    [6, 7, 8, 9, 10],
    [11, 12, 13, 14, 15],
    [16, 17, 18, 19, 20],
    [21, 22, 23, 24, 25],
    ];

    const res: number[] = [];

    // 顺时针遍历
    forEachAround(arr, (v) => res.push(v));
    console.log(res); // [1, 2, 3, 4, 5, 10, 15, 20, 25, 24, 23, 22, 21, 16, 11, 6, 7, 8, 9, 14, 19, 18, 17, 12, 13]

    res.length = 0;
    // 逆时针遍历
    forEachAround(arr, (v) => res.push(v), {reverse: true});
    console.log(res); // [1, 6, 11, 16, 21, 22, 23, 24, 25, 20, 15, 10, 5, 4, 3, 2, 7, 12, 17, 18, 19, 14, 9, 8, 13]

    res.length = 0;
    // 只遍历最外面一圈
    forEachAround(arr, (v, i): false | void => {
    if (i[0] === 1 && i[1] === 1) return false;
    res.push(v);
    });
    console.log(res); // [1, 2, 3, 4, 5, 10, 15, 20, 25, 24, 23, 22, 21, 16, 11, 6]

    res.length = 0;
    // 只遍历最外面一圈,并且跳过第一层
    forEachAround(arr, (v, i): false | void => {
    if (i[0] === 0 && i[1] === 0) {
    // 移动到第二行倒数第二列
    i[0] = 1;
    i[1] = 3;
    return;
    }
    if (i[0] === 1 && i[1] === 1) return false;
    res.push(v);
    });
    console.log(res); // [10, 15, 20, 25, 24, 23, 22, 21, 16, 11, 6]

    res.length = 0;
    // 只遍历最外面一圈,并且跳过第一层(使用startIndexes和startDirect)
    forEachAround(
    arr,
    (v, i): false | void => {
    res.push(v);
    if (i[0] === 0 && i[1] === 0) return false;
    },
    { startIndexes: [1, 4], startDirect: 'bottom' },
    );
    console.log(res); // [10, 15, 20, 25, 24, 23, 22, 21, 16, 11, 6, 1]