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]); // 5 console.log(typeof {name:2});// 6 console.log(typeof function(){return 2});// function 7 console.log(typeof new Date());// 8 console.log(typeof null); // 9 console.log(typeof undefined);// undefined
但typeof只能区分数字、字符串、布尔值、方法及undefined,其他的对象、数组、日期、null等均为 ,还是没能区分开,
我们可以利用 .prototype.toString.call实现。
1 var getType = .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 [ Number] 2 [ String] 3 [ Boolean] 4 [ Array] 5 [ ] 6 [ Function] 7 [ Date] 8 [ Null] 9 [ Undefined]
这样就能具体区分JS中的数据类型了。
原理请参考这里。
继续阅读与本文标签相同的文章
上一篇 :
一张图看懂杭州·云栖大会的前世今生
-
滴滴 这是一见钟情的感脚
2026-05-18栏目: 教程
-
以实践的方式讨论:N-Gram原理与其应用
2026-05-18栏目: 教程
-
Hi拼团,第六代云服务器拼团购买更便宜,低至148元/年
2026-05-18栏目: 教程
-
汇编(五)栈、CPU提供的栈机制、push、pop指令
2026-05-18栏目: 教程
-
为什么绝大部分公司用钉钉上班不用微信,其实原因很简单
2026-05-18栏目: 教程
