首页 > 编程知识 正文

typeof操作符以字符串形式返回变量的数据类型,typeof不能返回的数据类型

时间:2023-05-04 00:56:26 阅读:285503 作者:3242

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();

}

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

 

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。