typeof返回的六种数据类型

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_41695090/article/details/80942163

typeof 共返回6种数据格式:

1、object 

2、undefined

3、string

4、number

5、boolean

6、function

特别注意Array和null返回的都是object 

function show() {

            console.log("var x; typeof(x) : "+typeof(x));    // undefined
            console.log("typeof(10) : "+typeof(10));   // number
            console.log("typeof('abc') : "+typeof('abc')); // string
            console.log("typeof(true)"+typeof(true));  // boolean

            console.log("typeof(function () { }) : "+typeof(function () { }));  //function
 
            console.log("typeof([1, 'a', true]) : "+typeof([1, 'a', true]));  //object
            console.log("typeof ({ a: 10, b: 20 }) : "+typeof ({ a: 10, b: 20 }));  //object
            console.log("typeof (new Number(10)) : "+typeof (new Number(10)));  //object
            console.log("typeof ($) : "+typeof ($)); //function 
            console.log("typeof (null) : "+typeof (null)); //Object
            console.log("typeof (undefined) : "+typeof (undefined)); //undefined

        }

由此可见,这种数据类型检测存在一些弊端

我们可以自己来创建一种数据检测方式,如下

function toType (obj) {
  return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase();

}

这样对于结果的检测就完善了许多

猜你喜欢

转载自blog.csdn.net/sinat_41695090/article/details/80942163