typeof和construct区别?

 

平时调试的时候经常需要用到打印出数据的类型,之前常用的是typeof基本可以解决问题,但是有一次打印的时候发现一个数组对象打印类型的时候打印的是object,如下:

let fruit = ["apple","pine","orange","banana"];
console.log("typeof(fruit)-----"+typeof(fruit));
//typeof(fruit)-----object

但实际我想看到的array,所以可以用constructor来查看,如下:

let fruit = ["apple","pine","orange","banana"];
console.log("typeof(fruit)------"+typeof(fruit));
console.log("fruit.constructor------"+fruit.constructor);
//typeof(fruit)------object
//fruit.constructor------function Array() { [native code] }

后面了解了一下两者的区别:

  • 使用typeof可以确定的JavaScript的变量类型如下:
变量   数据类型
typeof(“bill”) string
typeof(3.14) number
typeof(NaN) number
typeof(false) boolean
typeof([0,2,3,1,2]) object
typeof({name:‘bill’,age:16}) object
typeof(new Date()) object
typeof(function(){}) function
typeof(mycar) undefined
typeof(null) object
  • 使用constructor属性返回所有JavaScript变量的构造函数
变量   数据类型
‘bill’.constructor String()
3.14.constructor Number()
false.constructor Boolean()
[0,1,2,3,4].constructor Array()
{name:‘bill’,age:16}.constructor Object()
(new Date()).constructor Date()
(function(){}).constructor Function()

//所以实际上不止数组,还有日期,用typeof是判断不出来的,用构造器是可以的,百度得知constructor在类继承时会有问题,因为涉及不多所以就不记录了

总结:通常情况下用typtof判断就可以了,可根据情况选择constructor或者instanceof或者prototype,prototype胜在通用但是比较繁琐,一般不用

posted @ 2021-01-23 16:31  会转圈圈的哆瑞米  阅读(114)  评论(0编辑  收藏  举报