需要遍历的数组
回调函数
可选
start开始时的index,默认[0, 0]
可选
start开始时的方向,默认向右('right'),reverse为true时向左('left')
可选
reverse?: boolean是否逆时针遍历;默认为false,顺时针遍历
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]
环绕式遍历数组