目录
数据类型
基本数据类型
String(字符串)、Number(数字)、Boolean(布尔)、Undefined(未定义)、Null(空)、Symbol(独一无二的值)、BigInt(大整数)
复杂数据类型
Object(Map、Set、Person)、Array(数组)、Function(函数)
数据类型判断
typeof
js提供了typeof 能够很准确的判断基本数据类型,对于数组或者Map, Set这种数据类型不能够很友好的进行判断.
typeof 42; // "number"
typeof 'hello'; // "string"
typeof true; // "boolean"
typeof undefined; // "undefined"
typeof null; // "object"
typeof Symbol(1) // "symbol"
typeof BigInt(1) // "bigint"
typeof {}; // "object"
typeof []; // "object"
typeof new Map() // "object"
typeof new Set() // "object"
typeof function() {}; // "function"
Object.prototype.toString
对于js内置的数据类型都能判断,比如Array、Set、Map、Null,但是对于自定义的类无法做判断
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(null); // "[object Null]"
Object.prototype.toString.call(Symbol(1)); // "[object Symbol]"
Object.prototype.toString.call(BigInt(1)); // "[object BigInt]"
Object.prototype.toString.call({}); // "[object Object]"
Object.prototype.toString.call([]); // "[object Array]"
Object.prototype.toString.call(new Set()); // "[object Set]"
Object.prototype.toString.call(new Map()); // "[object Map]"
Object.prototype.toString.call(function() {}); // "[object Function]"
function Person(){} // 自定义类
const p = new Person()
class Animal { // 自定义类
construtor(){}
}
const cat = new Animal ()
Object.prototype.toString.call(cat); // "[object Object]"
Object.prototype.toString.call(new p()); // "[object Object]"
instanceof
运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上,只做复杂数据类型的判断
{} instanceof Object; // true
[] instanceof Array; // true
function() {} instanceof Function; // true
function Person(){}
const p = new Person()
class Animal {
construtor(){}
}
const cat = new Animal ()
cat instanceof Animal; // true
p instanceof Person; // true
new Map() instanceof Map; // true
new Set() instanceof Set; // true
Array.isArray 方法
判断一个值是否是数组
Array.isArray([]); // true
Array.isArray({}); // false
Array.isArray('hello'); // false
总结
如果要判断基本数据类型可以用typeof、如果判断复杂数据类型可以用instanceof