如何在JavaScript中生成指定端点的二维坐标数组?
实现代码
基础版(双重循环,可读性最高)
function generateCoords(max) { const res = []; for (let x = 1; x <= max; x++) { for (let y = 1; y <= max; y++) { res.push([x, y]); } } return res; } // 测试示例 console.log(generateCoords(3)); // 输出:[[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]]
简洁版(数组内置方法,无显式循环)
const generateCoords = max => Array.from({length: max}, (_, i) => i + 1) .flatMap(x => Array.from({length: max}, (_, j) => [x, j + 1]));
补充说明
如果需要增加入参校验,避免非法输入,可以在函数开头加入判断逻辑:
function generateCoords(max) { if (typeof max !== 'number' || !Number.isInteger(max) || max < 1) { throw new TypeError('入参必须为大于0的正整数'); } const res = []; for (let x = 1; x <= max; x++) { for (let y = 1; y <= max; y++) { res.push([x, y]); } } return res; }
内容的提问来源于stack exchange,提问作者zeidb
相关产品推荐
相关产品推荐

