// 判断是否是数字类型的方法
// 方法一:使用 typeof 操作符
function isNumberType(value) {
return typeof value === 'number' && !isNaN(value);
}
// 解释:typeof 操作符可以判断一个值的类型,对于数字类型会返回 'number'。但是需要注意的是,NaN 的类型也是 'number',所以我们需要额外使用 isNaN 函数来排除 NaN。
// 示例:
console.log(isNumberType(123)); // true
console.log(isNumberType('123')); // false
console.log(isNumberType(NaN)); // false
// 方法二:使用 Number.isFinite 方法
function isNumberTypeUsingIsFinite(value) {
return Number.isFinite(value);
}
// 解释:Number.isFinite 方法可以判断一个值是否为有限的数字(即不是 Infinity、-Infinity 或 NaN),并且它不会将字符串或其它非数字类型的值视为数字。
// 示例:
console.log(isNumberTypeUsingIsFinite(123)); // true
console.log(isNumberTypeUsingIsFinite('123')); // false
console.log(isNumberTypeUsingIsFinite(NaN)); // false
console.log(isNumberTypeUsingIsFinite(Infinity)); // false
上一篇:js 判断key是否存在
下一篇:js 判断{}
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站