返回
想从类型检测的海洋脱颖而出?不妨来瞧瞧typeof和instanceof吧!
前端
2023-11-21 11:14:08
瞧瞧typeof如何检测数据类型
typeof,javascript中非常灵活的一个操作符,能够嗅探变量类型。瞧,typeof与六种基本类型交手:
- typeof [1, 2, 3] => "object"
- typeof { a: 'a', b: 'b' } => "object"
- typeof "hello" => "string"
- typeof new Date() => "object"
- typeof true => "boolean"
- typeof new RegExp() => "object"
除了这六种基本类型,typeof还与一些特殊值交手:
- typeof [] => "object"
- typeof /hello/ => "object"
- typeof 1 => "number"
- typeof 'hello' => "string"
- typeof false => "boolean"
- typeof null => "object",这一点似乎有点奇怪,但它是由一个历史遗留错误导致的。
- typeof new Function() => "function"
- typeof new Error() => "object"
- typeof undefined => "undefined"
- typeof symbol => "symbol",前提是你的javascript版本高于ES6。
instanceOf是如何审查对象出身的
instanceof是如何审查对象出身的呢?我们看看它的审讯过程:
- [].instanceof Array => true
- {a:'a', b:'b'}.instanceof Object => true
- "hello".instanceof String => true
- new Date().instanceof Date => true
- true.instanceof Boolean => true
- new RegExp().instanceof RegExp => true
- [] instanceof Array => true
- /hello/ instanceof RegExp => true
- 1 instanceof Number => false
- 'hello' instanceof String => false
- false instanceof Boolean => false
- null instanceof Object => false
- new Function() instanceof Function => true
- new Error() instanceof Error => true
- undefined instanceof undefined => false
- Symbol() instanceof Symbol => true,前提是你的javascript版本高于ES6。
与typeof相比,instanceof的操作模式显然更受限制。它的作用更像是检查一个变量是否属于某种特定的类。
揭秘typeof和instanceof之间的微妙差异
- 对于基本类型,typeof和instanceof的检测结果是相同的。 但请注意typeof null => "object"的例外情况。
- 对于对象类型,typeof永远返回"object",而instanceof可以进一步识别出具体的对象类型。 比如,instanceof可以告诉你一个变量是属于Array、Date、RegExp等类型。
- instanceof不能用于检测基本类型,而typeof可以。
- instanceof对于null的检测结果为false,而typeof返回"object"。
从类型检测的汪洋中脱颖而出
typeof和instanceof是javascript中两个非常重要的类型检测操作符。掌握了它们,您就可以在类型检测的海洋中畅游无阻。
- typeof适用于基本类型和对象类型。
- instanceof只适用于对象类型。
- instanceof可以进一步识别出具体的对象类型,而typeof只能返回"object"。
- instanceof对于null的检测结果为false,而typeof返回"object"。