console.log(typeof 11);
console.log(typeof "alex");
console.log(typeof null);
console.log(typeof true);
console.log(typeof undefined);
console.log(typeof [12, 3]);
console.log(typeof { name: "alex" });
console.log(typeof function () { });
console.log(typeof BigInt(123));
console.log(typeof Symbol("Alex"));
// number 能
// string 能
// object 不能
// boolean 能
// undefined能
// object 不能
// object 不能
// function 能
// bigint 能
// symbol 能
// 总结来说typeof只能判断对应的基础值类型原始类型
以上就是typeof的判断类型
//原理是判断在其原型链能否找到该类型的原型
var alex = { name: "alex" }
console.log(12 instanceof Number);
console.log("str" instanceof String);
console.log(true instanceof Boolean);
console.log(null == null);
console.log(undefined == null);
console.log(undefined === null);
console.log([1, 2] instanceof Array);
console.log(alex instanceof Object);
console.log(function () { } instanceof Function);
//只能判断引用类型原型链上
// false
// false
// false
// true
// true
// false
// true
// true
// true
// 注意对应的null的判断
以上是instanceof的判断类型
console.log((2).constructor === Number);
console.log(("str").constructor === String);
console.log((true).constructor === Boolean);
console.log(([]).constructor === Array);
console.log(({}).constructor === Object);
console.log((() => { }).constructor === Function);
// 使用对应的constructor构造函数来判断对应的是否是对应的引用类型还是原始类型
// 有两个作用,一是可以判断类型,二是对象实例可以通过范围constructor来访问到构造函数,如果创建一个对象那个来改变它的原型,那么就不能判断类型了
function People(name) {
this.name = name
}
// 更改对应的原型链指向
People.prototype = new Array()
var alex = new People("alex")
// 实例对象的constructor指向的是类的prototype
console.log(alex.constructor === People);
console.log(alex.constructor === Array);
以上是constructor的判断类型
//使用Object.prototype.toString判断数据类型
var a = Object.prototype.toString;
// 包装类是Number将包装类转为字符串
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));
// [object Number]
// [object Boolean]
// [object String]
// [object Array]
// [object Function]
// [object Object]
// [object Undefined]
// [object Null]
// Object的原型的方法是toString,但是Array和function等类型作为Object的实例重写了toString方法,想要得到对应的具体类型需要调用Object原型的toString方法
以上是Object.prototype.toString判断类型,常用的判断类型方式就这几种