参考答案:
对于原始类型来说,除了 null 都可以调用typeof显示正确的类型。
1typeof 1 // 'number' 2typeof '1' // 'string' 3typeof undefined // 'undefined' 4typeof true // 'boolean' 5typeof Symbol() // 'symbol' 6
但对于引用数据类型,除了函数之外,都会显示"object"。
1typeof [] // 'object' 2typeof {} // 'object' 3typeof console.log // 'function' 4
因此采用typeof判断对象数据类型是不合适的,采用instanceof会更好,instanceof的原理是基于原型链的查询,只要处于原型链中,判断永远为true
1 2const Person = function() {} 3const p1 = new Person() 4p1 instanceof Person // true 5var str1 = 'hello world' 6str1 instanceof String // false 7var str2 = new String('hello world') 8str2 instanceof String // true 9
最近更新时间:2024-08-10