在JavaScript开发中,函数参数校验是保障代码逻辑正确运行的基础,未做校验的参数很容易引发类型错误、空值异常等问题,影响程序稳定性。合理的参数校验和异常处理机制,可以有效降低这类问题的发生概率。

基础参数校验定义方式
最基础的参数校验方式是在函数内部直接对参数进行判断,这种方式实现简单,适合参数较少的场景。
function add(a, b) {
// 校验参数是否为数字类型
if (typeof a !== 'number') {
throw new TypeError('参数a必须是数字类型');
}
if (typeof b !== 'number') {
throw new TypeError('参数b必须是数字类型');
}
return a + b;
}
// 调用时传入非数字参数会直接抛出错误
// add('1', 2); // 报错:参数a必须是数字类型
结合默认参数的校验
ES6的默认参数可以和校验逻辑结合,先给参数设置默认值,再判断默认值是否符合要求,避免参数缺失的情况。
function getUserInfo(name = '默认用户', age = 0) {
// 校验name是否为字符串
if (typeof name !== 'string') {
throw new TypeError('name参数必须是字符串');
}
// 校验age是否为数字且非负
if (typeof age !== 'number' || age < 0) {
throw new RangeError('age参数必须是非负数字');
}
return { name, age };
}
// 正常调用
console.log(getUserInfo('张三', 20)); // { name: '张三', age: 20 }
使用defineProperty定义统一校验规则
如果多个函数需要相同的参数校验规则,可以使用Object.defineProperty定义统一的校验属性,减少重复代码。
// 定义参数校验的工具对象
const paramValidator = {};
// 定义数字类型校验规则
Object.defineProperty(paramValidator, 'number', {
value: function (val, paramName) {
if (typeof val !== 'number') {
throw new TypeError(`${paramName}必须是数字类型`);
}
return val;
},
writable: false,
enumerable: true,
configurable: false
});
// 定义字符串类型校验规则
Object.defineProperty(paramValidator, 'string', {
value: function (val, paramName) {
if (typeof val !== 'string') {
throw new TypeError(`${paramName}必须是字符串类型`);
}
return val;
},
writable: false,
enumerable: true,
configurable: false
});
function calculateArea(width, height) {
// 使用统一校验规则
const validWidth = paramValidator.number(width, 'width');
const validHeight = paramValidator.number(height, 'height');
return validWidth * validHeight;
}
// 校验失败会抛出对应错误
// calculateArea('10', 20); // 报错:width必须是数字类型
参数校验的异常处理方法
参数校验失败后的异常处理主要有两种常见方式,开发者可以根据业务场景选择。
抛出自定义错误
这种方式适合参数错误属于不可恢复的场景,直接抛出错误终止程序执行,上层调用方可以通过try catch捕获处理。
function divide(a, b) {
if (typeof a !== 'number' || typeof b !== 'number') {
throw new TypeError('两个参数都必须是数字类型');
}
if (b === 0) {
throw new RangeError('除数不能为0');
}
return a / b;
}
// 上层调用捕获错误
try {
divide(10, 0);
} catch (err) {
console.error('计算失败:', err.message);
}
返回统一错误对象
这种方式适合需要友好返回错误信息的场景,函数不抛出错误,而是返回包含成功状态和错误信息的对象,调用方根据状态判断后续逻辑。
function updateUser(id, userInfo) {
// 校验参数
if (typeof id !== 'number') {
return {
success: false,
error: '用户id必须是数字类型'
};
}
if (typeof userInfo !== 'object' || userInfo === null) {
return {
success: false,
error: '用户信息必须是对象类型'
};
}
// 模拟更新逻辑
return {
success: true,
data: { id, ...userInfo }
};
}
const result = updateUser('1', { name: '李四' });
if (!result.success) {
console.error('更新失败:', result.error);
}
不同校验方式对比
以下是几种常见参数校验方式的特点对比,方便开发者选择适合的方案:
| 校验方式 | 实现复杂度 | 适用场景 | 缺点 |
|---|---|---|---|
| 函数内基础校验 | 低 | 参数少、逻辑简单的函数 | 重复代码多,不适合多函数复用 |
| 默认参数结合校验 | 低 | 有默认参数需求的函数 | 校验逻辑和函数耦合度高 |
| defineProperty统一校验 | 中 | 多函数复用相同校验规则 | 需要提前定义校验工具对象 |
JS函数参数校验defineProperty异常处理类型检查修改时间:2026-06-27 05:42:18