首页 > 奇闻 > 正文内容

手把手教你用JS判断数字、字符串、对象类型

奇闻2025-05-28 06:25:24

各位刚入门JS的萌新们,是不是经常遇到这样的抓狂时刻?表单里用户输入的数字突然变成字符串,API返回的数据不知道是对象还是数组,就像新手如何快速入门JS类型判断却总被坑得怀疑人生。今天咱们就掰开揉碎讲透这三个最常碰到的类型判断,保你学完就能实操!


??一、数字类型检测的坑与招??
先来看这个经典场景:

javascript复制
const price = document.getElementById('price').value
console.log(typeof price) // 你猜输出啥?

当用户输入"150"时,这里妥妥输出"string",惊不惊喜?这时候就需要真正的数字检测方法了。

??正确姿势三连??:

  1. ??typeof + isNaN组合拳??:
javascript复制
function isNumber(val) {
  return typeof val === 'number' && !isNaN(val)
}
// 测试用例
isNumber(42)       // true
isNumber("42")     // false
isNumber(NaN)      // false
  1. ??Object.prototype.toString绝杀技??:
javascript复制
Object.prototype.toString.call(42) // "[object Number]"
  1. ??Number.isFinite进阶版??:
javascript复制
Number.isFinite(Infinity)  // false
Number.isFinite(3.14)      // true

(看到这里先别急着关页面,后面还有更劲爆的字符串检测技巧)


??二、字符串类型鉴别的明暗战线??
你以为用typeof就能搞定?看看这个案例:

javascript复制
const str = new String("hello")
console.log(typeof str)   // "object" 
console.log(typeof "hi")  // "string"

同样的内容,字面量和对象形式居然检测结果不同!这时候就需要:

??双重验证法??:

  1. ??基础检测先用typeof??:
javascript复制
typeof variable === 'string'
  1. ??处理包装对象用toString??:
javascript复制
Object.prototype.toString.call(str) === "[object String]"

??对比表格看差异??:

检测方式"hello"new String("hi")123
typeofstringobjectnumber
instanceof Stringfalsetruefalse
toString.call[object String][object String][object Number]

??三、对象类型识别的三重门??
很多新手在这里栽跟头,看这段代码:

javascript复制
console.log(typeof null)      // "object"
console.log(typeof [1,2,3])   // "object"
console.log(typeof {})        // "object"

这三个都返回object,但其实是完全不同的数据类型!正确判断姿势:

??精准检测三步走??:

  1. ??排除null干扰项??:
javascript复制
if(value && typeof value === 'object'){
    // 到这里才是真对象
}
  1. ??构造函数验证法??:
javascript复制
({}).constructor === Object // true
([]).constructor === Array // true
  1. ??终极万能检测式??:
javascript复制
Object.prototype.toString.call({}) === "[object Object]"

??小编的深夜踩坑实录??:
去年做支付系统时,因为没处理好金额类型检测,导致用户输入"100元"时系统直接崩溃。现在我的开发守则是:

  1. 永远先用typeof做第一层过滤
  2. 处理用户输入必用Number()转换
  3. 关键数据必须用Object.prototype.toString复核
  4. 看到typeof null返回object就条件反射写排除逻辑

最后说句大实话:类型检测就像验钞机,平时觉得多余,关键时刻能救命!下次写代码时多花30秒做类型判断,能省下3小时debug时间你信不信?

搜索