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

JS闭包实现矩形周长面积安全计算:代码验证问题排查

问题分析与解决方案

一、原代码中“边长严格大于0”验证不生效的原因

  • 参数处理错误:设置边长的arr[0]函数只定义了一个参数newSum,但调用时传了两个参数(2,2),第二个参数完全没被处理;而且x和y都被赋值为同一个newSum,本质是在处理正方形而非矩形。
  • 验证逻辑错误:判断条件写的是newSum >= 0,允许了0值,完全没实现“严格大于0”的要求;就算传负数,比如sqrt[0](-1),只是不赋值,但初始x、y是0,依然会用0计算周长和面积,不符合需求。
  • 无类型校验:根本没做任何类型验证,随便传字符串、对象都会被赋值(比如sqrt[0]('abc'),x和y会变成字符串,计算时出现非预期结果)。

二、如何验证边长为严格大于0的Number类型

需要同时满足三个校验条件:

  • 用typeof val === 'number'判断基础类型为数字
  • 用Number.isFinite(val)排除NaN、Infinity这类无效数字(因为typeof NaN也是number)
  • 加上val > 0确保边长严格大于0

三、修正后的安全闭包代码

function createRectangleCalculator() {
  let width = null;
  let height = null;

  // 校验边长合法性的工具函数
  function isValidSide(side) {
    return typeof side === 'number' && Number.isFinite(side) && side > 0;
  }

  return {
    // 设置矩形的宽和高
    setDimensions: function(w, h) {
      if (isValidSide(w) && isValidSide(h)) {
        width = w;
        height = h;
      } else {
        throw new Error('边长必须是严格大于0的有效数字');
      }
    },
    // 计算周长
    getPerimeter: function() {
      if (width === null || height === null) {
        throw new Error('请先设置合法的矩形边长');
      }
      return 2 * (width + height);
    },
    // 计算面积
    getArea: function() {
      if (width === null || height === null) {
        throw new Error('请先设置合法的矩形边长');
      }
      return width * height;
    }
  };
}

// 使用示例
const calc = createRectangleCalculator();
calc.setDimensions(2, 3);
console.log(calc.getPerimeter()); // 输出10
console.log(calc.getArea()); // 输出6

// 错误测试(取消注释可验证)
// calc.setDimensions(-1, 2); // 抛出错误
// calc.setDimensions('2', 3); // 抛出错误
// calc.getPerimeter(); // 未设置边长时抛出错误

这个优化后的代码做了这些改进:

  • 用对象返回方法,语义化更强(setDimensions、getPerimeter比数组索引更易理解)
  • 初始值设为null,避免未设置边长时用0计算
  • 加入完整的类型和范围校验,不合法时抛出明确错误
  • 提取工具函数isValidSide,避免代码重复

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 14:40:32