JS 类型判断
标签(空格分隔): JS 类型 typeof instance Object.prototype.toString.call
1.typeof
只能区分 字符串 、对象、布尔、function 、number、undefined
不能区分:对象里的详细类型;例如 对象里的 数组、null 等等 (如何判断,写在 3 内容里了)
特别注意不能区分null(null是object)
Value Class Type
-------------------------------------
"foo" String string
new String("foo") String object
1.2 Number number
new Number(1.2) Number object
true Boolean boolean
new Boolean(true) Boolean object
new Date() Date object
new Error() Error object
[1,2,3] Array object
new Array(1, 2, 3) Array object
new Function("") Function function
/abc/g RegExp object (function in Nitro/V8)
new RegExp("meow") RegExp object (function in Nitro/V8)
{} Object object
new Object() Object object
2. instanceof
只能原型链是构造函数的数据,否则判断不出来
例如:
可判断 元素 是否为 数组:
[] instanceof Array // true
null instanceof Object // false
typeof null // "object"
??? 如何解决判断不了 对象里 的数据类型呢?
3.Object.prototype.toString.call(xx) // [Object xx]
只检测 对象里的具体类型 ======== 补充 typoof 的判断
参考文章:https://bonsaiden.github.io/JavaScript-Garden/zh/#types.typeof
Object.prototype.toString.call([]) // "[object Array]"
Object.prototype.toString.call( null ) // "[object Null]"