当前位置: 移动技术网 > IT编程>开发语言>JavaScript > JS判断类型

JS判断类型

2018年10月09日  | 移动技术网IT编程  | 我要评论

长安运通,北京的二本大学,mtk解决方案

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中的数据类型了。

原理请参考。

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网