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

如何在JavaScript中编写pointsToPolygon静态方法?

JS实现pointsToPolygon静态方法方案

前提说明

默认你已经定义了基础Point类(一般包含x、y坐标属性)和Polygon类(构造函数支持接收顶点数组作为入参),如果没有对应定义可以参考下文的示例代码。

完整实现代码

// 参考基础类定义,你已有对应类的话可以直接跳过
class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
}

class Polygon {
  constructor(vertices = []) {
    this.vertices = vertices;
  }
}

// 工具类挂载静态方法实现
class GeometryUtil {
  /**
   * 入参Point数组转换为Polygon对象
   * @param {Point[]} pts Point类型的顶点数组
   * @returns {Polygon} 新生成的Polygon实例引用
   * @throws 入参不合法时抛出类型错误
   */
  static pointsToPolygon(pts) {
    // 入参合法性校验,*可选但推荐添加*
    if (!Array.isArray(pts)) {
      throw new TypeError('入参必须为数组类型');
    }
    const isAllPoint = pts.every(item => item instanceof Point);
    if (!isAllPoint) {
      throw new TypeError('数组所有元素必须为Point类实例');
    }
    // 生成并返回Polygon实例
    return new Polygon(pts);
  }
}

使用示例

// 构造测试顶点
const p1 = new Point(0, 0);
const p2 = new Point(20, 0);
const p3 = new Point(20, 20);
const p4 = new Point(0, 20);

// 调用静态方法生成多边形
const rect = GeometryUtil.pointsToPolygon([p1, p2, p3, p4]);
console.log(rect.vertices) // 输出传入的4个Point实例数组

可选优化方案

如果希望静态方法直接挂载到Polygon类本身,可以调整为如下写法,调用更直观:

class Polygon {
  constructor(vertices = []) {
    this.vertices = vertices;
  }

  static pointsToPolygon(pts) {
    // 校验逻辑和上文一致
    if (!Array.isArray(pts) || !pts.every(item => item instanceof Point)) {
      throw new TypeError('入参不合法');
    }
    return new this(pts);
  }
}

// 调用方式
const rect = Polygon.pointsToPolygon([p1, p2, p3, p4]);

注意事项

  • 如果你的Polygon类构造函数入参规则和示例不同,只需要调整new Polygon()的传参逻辑即可,整体方法结构不需要修改
  • 入参校验逻辑可以根据业务需求增减,不需要校验的情况下可以直接删除对应判断,提升运行效率

内容的提问来源于stack exchange,提问作者evanl11

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 04:27:03