You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 16:27:03