1. Use the typeof operator:
typeof is a unary operator that returns the data type string of a value. It provides basic type information for most data types, including "number", "string", "boolean", "undefined", "symbol", "object" (including null), and "function". For example:
typeof 42; // "number"
typeof "Hello"; // "string"
typeof true; // "boolean"
typeof undefined; // "undefined"
typeof Symbol("symbol"); // "symbol"
typeof {
}; // "object"
typeof []; // "object"
typeof null; // "object"(这是 typeof 的一个历史性 bug)
typeof function(){
}; // "function"
It should be noted that typeof null returns "object", which is a legacy problem, in fact null is a special basic data type.
2. Use the instanceof operator:
instanceof is used to determine whether an object is an instance created by a constructor. For example:
[] instanceof Array; // true
{
} instanceof Object; // true
new Date() instanceof Date; // true
instanceof can only judge data of reference type, and cannot be used for basic data types.
3. Use the Object.prototype.toString.call() method:
This is a general method that can be used to obtain precise type information for variables. For example:
Object.prototype.toString.call(42); // "[object Number]"
Object.prototype.toString.call("Hello"); // "[object String]"
Object.prototype.toString.call(true); // "[object Boolean]"
Object.prototype.toString.call(undefined); // "[object Undefined]"
Object.prototype.toString.call(Symbol("symbol")); // "[object Symbol]"
Object.prototype.toString.call({
}); // "[object Object]"
Object.prototype.toString.call([]); // "[object Array]"
Object.prototype.toString.call(null); // "[object Null]"
Object.prototype.toString.call(function(){
}); // "[object Function]"
By calling the Object.prototype.toString.call() method, you can get a string expressed in the format of "[object type]", where the type is the exact type of the variable.
4. Use the strict equality operator ===
1 === 1; // true,数值相等且类型相同
"hello" === "hello"; // true,字符串相等且类型相同
true === true; // true,布尔值相等且类型相同
undefined === undefined; // true,undefined 相等且类型相同
null === null; // true,null 相等且类型相同
1 === "1"; // false,数值类型与字符串类型不同
true === 1; // false,布尔值类型与数值类型不同
null === undefined; // false,null 和 undefined 是不同的类型
Using === can make more accurate data type judgments, because it requires the same type when comparing values. But it should be noted that for the comparison of reference types, === will compare whether their reference addresses are the same, not whether their values are equal. For example:
Symbol("symbol") === Symbol("symbol"); // false,Symbol 值是唯一的
{
} === {
}; // false,对象是引用类型,比较的是引用地址
[] === []; // false,同样的原因,数组是引用类型
const obj1 = {
};
const obj2 = {
};
const obj3 = obj1;
obj1 === obj2; // false,obj1 和 obj2 指向不同的对象
obj1 === obj3; // true,obj1 和 obj3 指向同一个对象