码迷,mamicode.com
首页 > Web开发 > 详细

JS区分数据类型

时间:2018-10-09 14:24:46      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:参考   new   依次   number   turn   数字   call   func   return   

JS中的typeof方法可以查看数据的类型,如下:

1 console.log(typeof 2); // number
2 console.log(typeof "2"); // string
3 console.log(typeof true); // boolean
4 console.log(typeof [2]); // object
5 console.log(typeof {name:2});// object
6 console.log(typeof function(){return 2});// function
7 console.log(typeof new Date());// object
8 console.log(typeof null); // object
9 console.log(typeof undefined);// undefined

但typeof只能区分数字、字符串、布尔值、方法及undefined,其他的对象、数组、日期、null等均为object,还是没能区分开,

我们可以利用Object.prototype.toString.call实现。

 1 var getType = Object.prototype.toString;
 2 var res = getType.call(2);
 3 res = getType.call("2");
 4 res = getType.call(true);
 5 res = getType.call([2]);
 6 res = getType.call({name:2});
 7 res = getType.call(function(){});
 8 res = getType.call(new Date());
 9 res = getType.call(null);
10 res = getType.call(undefined);

输出结果依次为:

1 [object Number]
2 [object String]
3 [object Boolean]
4 [object Array]
5 [object Object]
6 [object Function]
7 [object Date]
8 [object Null]
9 [object Undefined]

这样就能具体区分JS中的数据类型了。

原理请参考这里

 

JS区分数据类型

标签:参考   new   依次   number   turn   数字   call   func   return   

原文地址:https://www.cnblogs.com/jyughynj/p/9749712.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!