javascript 判断数据类型的方法
1. typeof
- 只能判断基础类型数据
- 遇到Object、Array、Null都会被判断为Object
console.log(typeof 2);
console.log(typeof true);
console.log(typeof 'str');
console.log(typeof function(){});
console.log(typeof undefined);
console.log(typeof {});
console.log(typeof []);
console.log(typeof null);
2. instanceof
- instanceof可以
正确地判断对象类型, - instanceof
不能判断普通类型。
console.log(2 instanceof Number);
console.log(true instanceof Boolean);
console.log('str' instanceof String);
console.log([] instanceof Array);
console.log(function(){} instanceof Function);
console.log({} instanceof Object);
3. constructor
- 这种方法需要通过通过原型访问到构造函数,如果这个
数据的原型被修改了,这个方法就行不通了
console.log((2).constructor === Number);
console.log((true).constructor === Boolean);
console.log(('str').constructor === String);
console.log(([]).constructor === Array);
console.log((function() {}).constructor === Function);
console.log(({}).constructor === Object);
4. Object.prototype.toString.call()
- 通过对象原型上的的toString方法可以判断类型
- 使用 .call() 是因为
Array 和 Function 数据类型重写了 .toString方法. - 只有原来的对象的toString方法才能判断类型。
let a = Object.prototype.toString;
console.log(a.call(2));
console.log(a.call(true));
console.log(a.call('str'));
console.log(a.call([]));
console.log(a.call(function(){}));
console.log(a.call({}));
console.log(a.call(undefined));
console.log(a.call(null));
相关文章
参考文章@笨成要先飞