typeof返回一个表达式的数据类型的字符串,返回结果为js基本的数据类型,包括number,boolean,string,object,undefined,function
js中constructor较少使用,如果不是搜索到相关construtor相关的资料,我之前从没有注意到js还有这个函数。
使用typeof的一个不好的地方就是它会把Array还有用户自定义函数都返回为object
1
<
script type
=
"
text/javascript
"
>
2 <! –
3 var j = 2 ;
4 alert( typeof (j)); // number
5 alert( " j.constructor: " + j.constructor); // function …
6 alert( typeof (j.constructor)); // function
7 // –>
8 < / script>
2 <! –
3 var j = 2 ;
4 alert( typeof (j)); // number
5 alert( " j.constructor: " + j.constructor); // function …
6 alert( typeof (j.constructor)); // function
7 // –>
8 < / script>
可以看到js.constructor返回的是一些字符串,大家都应该能看到这是一个function类型,此例为Number()为Number对象的构造函数,Number()用于将其参数转换为数字number类型,并返回转换结果(若不能转换则返回 NaN)。
因此在以后的js判断数据类型时可以使用以下方式来得到其详细数据类型
1
if((typeof o=="object") && (o.constructor==Number)){
2…
3}
2…
3}
这里还要注意,constructor只能对已有变量进行判断,而typeof则可对未声明变量进行判断(返回undefined)。
{}.constructor为function Object(){[Native code]}