1. typeof
console.log('数值', typeof 10); // number
console.log('布尔', typeof true); // boolean
console.log('字符串'. typeof ‘hello world’); // string
console.log('数组', typeof []); // object
console.log('对象', typeof {}); // object
console.log('函数'. typeof function() {}); // function
console.log('undefined', typeof undefined); // undefined
console.log('null', typeof null); // object
2. instanceof(检测某一个实例是否属于这个类,可以正确判断对象类型)
内部运行机制:判断它的原型链上是否能找到这个类型的原型
console.log("数值", 10 instanceof Number); // false
console.log("布尔", true instanceof Boolean); // false
console.log("字符串", "hello world" instanceof String); // false
console.log("数组", [] instanceof Array); // true
console.log("函数", function(){} instanceof Function); // true
console.log("对象", {} instanceof Object); // true
3. constructor(检测实例和类的关系,从而检测数据类型)引用原来构造该对象的函数
console.log("数值", (10).constructor === Number); // true
console.log("布尔", (true).constructor === Boolean); // true
console.log("字符串", ('hello world').constructor === String); // true
console.log("数组", ([]).constructor === Array); // true
console.log("函数", (function(){}).constructor === Function); // true
console.log("对象", ({}).constructor === Object); // true
4. Object.prototype.toString.call()
var a = Object.prototype.toString;
console.log('数值', a.call(10)); // [object Number]
console.log('布尔', a.call(true)); // [object Boolean]
console.log('字符串'. a.call('hello world')); // [object String]
console.log('数组', a.call([])); // [object Array]
console.log('对象', a.call({})); // [object Object]
console.log('函数'. a.call(function(){})); // [object Function]
console.log('undefined', a.call(undefined)); // [object Undefined]
console.log('null', a.call(null)); // [object Null]
5. 手写typeof
function myTypeOf(obj) {
return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase()
}
6. 手写instanceof
function myInstanceOf(oValue, target) {
//instanceof 只能判断引用类型数据
if(typeof oValue !== 'object' || oValue === null) return false;
let targetPro = target.prototype,
oValuePro = oValuePro.__proto__;
while (true) {
if(oValuePro === null) {
return false;
}
if(oValuePro === targetPro) {
return true;
}
oValuePro = oValuePro.__proto__
}
}
function instance(left, right) {
let proto = Object.getPrototypeOf(left);
let prototyppe = right.prototype;
while(true) {
if(!proto) {
return false;
}
if(proto === prototype) {
return true;
}
proto = Object.getPrototypeOf(proto);
}
}
7. 判断是否是数组
//通过原型方法
1. Object.prototype.toString.call([]).slice(8, -1) === 'Array';
//通过原型链
//对象的隐式原型等于构造函数的显式原型
2. [].__proto__ === Array.prototype;
//ES6方法
3. Array.isArray([]);
//instanceof
4. [] instanceof Array;
// 通过构造函数方式
5. Array.prototype.isPrototypeOf([])