[JS]类型判断之typeof

166 阅读1分钟

局限在于只能判断原始数据类型、以及引用类型Object(包括null)--这句话并不全对

// 字面量方式
// 原始数据类型
console.log(typeof 111); // number
console.log(typeof 'haha'); // string
console.log(typeof true); // boolean
console.log(typeof Symbol()); // symbol
console.log((typeof undefined)); // undefined
console.log(typeof 11n); // bigint
// 引用类型
console.log(typeof null); // object
console.log(typeof []); // object
console.log(typeof {}); // object

然而当你使用new方法创建数据时,情况会不一样。(如果你知道new方法做了什么,你就可以理解这个看起来有些诡异的事情了)

请在使用中避开以下陷阱

// new方式
const new_boolean = new Boolean(true); 
console.log(new_boolean); // [Boolean: true]
console.log(typeof new_boolean); // objectconst new_number = new Number(111);
console.log(new_number); // [Number: 111]
console.log(typeof new_number);  // objectconst new_string = new String('haha');
console.log(new_string); // [String: 'haha']
console.log(typeof new_string); //object//为什么呢?
console.log(new_boolean.constructor); // [Function: Boolean]

typeof 真的无法判断上述以外的其他类型了嘛?答案是否定的,实际上它可以判断出 function,甚至无论你使用哪一种函数声明方式

// typeof 可以判断 function
console.log(typeof function(){}); // function
// 函数表达式
const a = function () {
​
}
// 函数声明
function b() {}
// 使用构造函数
const c = new Function()
console.log(typeof a); // function
console.log(typeof b); // function
console.log(typeof c); // function

...next instanceof