You need to enable JavaScript to run this app. 在JavaScript中如何获取其他函数的参数以完成参数校验
优惠活动
大模型
产品
解决方案
定价
更多

在JavaScript中如何获取其他函数的参数以完成参数校验

代码存在的核心问题

  • 传参错误:调用withParamsCountValidation(3, test(1, 2))时,第二个参数是test(1,2)的执行结果,而非test函数本身,导致func拿到的不是函数类型,调用apply或者直接执行func都会报错。
  • 校验逻辑错误:
    1. 获取函数形参长度应该用func.length,而非执行checkFunc()后的返回值的length,直接调用checkFunc()属于无意义执行原函数
    2. 数字类型的count没有length属性,直接用count本身做判断即可
  • 错误抛出逻辑错误:
    1. 仅创建Error实例不会抛出异常,需要加throw关键字
    2. 错误信息的模板字符串语法错误,正确写法是new Error(报错内容),而非new Errorxxx()
  • 流程逻辑错误:第二个校验分支符合条件时仅写了true;没有任何中断逻辑,不管校验是否通过都会走到最后一行抛错的代码
  • 高阶函数逻辑缺失:需要返回一个包装后的校验函数,后续调用这个包装函数时才执行原逻辑,而非在定义阶段就直接执行校验

修正后的实现代码

const withParamsCountValidation = (count, func) => {
  // 先校验传入的func本身是不是函数
  if (typeof func !== 'function') {
    throw new Error('第二个参数必须传入函数类型');
  }
  const funcParamsLength = func.length;
  // 先做形参数量规则校验
  if (typeof count === 'number') {
    if (funcParamsLength !== count) {
      throw new Error(`函数的参数数量必须等于${count}`);
    }
  } else if (Array.isArray(count) && count.length === 2) {
    const [min, max] = count;
    if (funcParamsLength < min || funcParamsLength > max) {
      throw new Error(`函数的参数数量必须在${min}到${max}之间`);
    }
  } else {
    throw new Error('count参数只能是数字或者长度为2的数组');
  }
  // 返回包装后的函数,调用时才执行原函数,同时校验实参数量
  return function checkFunc(...args) {
    if (typeof count === 'number' && args.length !== count) {
      throw new Error(`调用时传入的参数数量必须等于${count}`);
    }
    if (Array.isArray(count)) {
      const [min, max] = count;
      if (args.length < min || args.length > max) {
        throw new Error(`调用时传入的参数数量必须在${min}到${max}之间`);
      }
    }
    return func.apply(this, args);
  }
};

// 正确使用方式:先传入函数本身得到包装后的校验函数
const validatedTest = withParamsCountValidation(3, test);
// 再调用包装后的函数传参执行
console.log(validatedTest(1, 2, 3)); // 输出6

function test(som, som2, som3) {
  return som + som2 + som3;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 12:30:03