使用JavaScript实现形状类层级及多图形总面积求和功能
现有代码核心问题
- 缺少存储图形实例的容器:
Answer类没有专门的属性存放创建的图形对象,所有add方法直接返回了单图面积,没有保留图形实例,无法完成多图求和需求 sumArea逻辑完全错误:当前代码是尝试对类方法本身做加法运算,不是对已创建的所有图形的面积求和,而且误用类名调用实例方法- 对「重叠计算」的理解有误:题目注意2明确说明即使重叠也直接求和,也就是说不需要计算图形重叠部分的扣减,直接把所有图形的单独面积相加即可,不需要额外处理几何重叠逻辑
- 你当前的
Rectangle实现是正方形逻辑,刚好匹配addSquare的方法需求,题目提到的矩形属于表述差异,无需调整
修复后的完整代码
// 形状类保持不变,符合「除构造函数外仅单个方法」的要求 class Rectangle { constructor(size) { this.size = size; } area() { return this.size * this.size; } } class Triangle { constructor(base, height) { this.base = base; this.height = height; } area() { return this.base * this.height / 2; } } class Circle { constructor(radius) { this.radius = radius; } area() { return Math.PI * this.radius ** 2; } } class Answer { constructor() { // 新增图形实例存储容器 this.shapes = []; } addTriangle(b, h) { // 创建实例后存入容器,不返回值符合void要求 this.shapes.push(new Triangle(b, h)); } addSquare(size) { this.shapes.push(new Rectangle(size)); } addCircle(radius) { this.shapes.push(new Circle(radius)); } sumArea() { let total = 0; // 用普通for循环遍历,性能优于forEach、reduce,符合优化要求 for (let i = 0; i < this.shapes.length; i++) { total += this.shapes[i].area(); } return total; } }
使用示例
// 测试用例 const ans = new Answer(); ans.addSquare(2); // 面积4 ans.addTriangle(3,4); // 面积6 ans.addCircle(2); // 面积约12.566 console.log(ans.sumArea()); // 输出总和约22.566
内容的提问来源于stack exchange,提问作者James
相关产品推荐
相关产品推荐

