JS 类型判断 的3种方式

来源:互联网 发布:淘宝宝贝发布物流 编辑:程序博客网 时间:2024/06/09 21:28

JS 类型判断

标签(空格分隔): JS 类型 typeof instance Object.prototype.toString.call


1.typeof

只能区分 字符串 、对象、布尔、function 、number、undefined

不能区分对象里的详细类型;例如 对象里的 数组、null 等等 (如何判断,写在 3 内容里了)
特别注意不能区分null(null是object)

Value               Class      Type-------------------------------------"foo"               String     stringnew String("foo")   String     object1.2                 Number     numbernew Number(1.2)     Number     objecttrue                Boolean    booleannew Boolean(true)   Boolean    objectnew Date()          Date       objectnew Error()         Error      object[1,2,3]             Array      objectnew Array(1, 2, 3)  Array      objectnew Function("")    Function   function/abc/g              RegExp     object (function in Nitro/V8)new RegExp("meow")  RegExp     object (function in Nitro/V8){}                  Object     objectnew Object()        Object     object

2. instanceof

只能原型链是构造函数的数据,否则判断不出来

例如:
可判断 元素 是否为 数组:

[] instanceof Array     // true null instanceof Object  // falsetypeof 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]"
原创粉丝点击