发布网友 发布时间:3小时前
共1个回答
热心网友 时间:3小时前
MDN:instanceof运算符用于检测构造函数的prototype属性是否出现在某个实例对象的原型链上。理解:判断在其原型链中能否找到该类型的原型。语法:object instanceof constructor
function D(){}
var o = new D();
o instanceof D; // true
o instanceof Object; // true
优点:能区分Array、Object和Function,适用于判断自定义的类实例对象
缺点:不能判断Number、Boolean、String基本数据类型
console.log(55 instanceof Number); // false
console.log(true instanceof Boolean); // false
console.log('aa' instanceof String); // false
console.log([] instanceof Array); // true
console.log(function(){} instanceof Function); // true
console.log({} instanceof Object); // true
String对象和Date对象都属于Object类型和一些特殊情况:
var simpleStr = "a simple string";
var objStr = new String();
var newStr = new String("String created with constructor");
var aDate = new Date();
var myNonObj = Object.create(null);
simpleStr instanceof String; // false,非对象实例,因此返回false
objStr instanceof String; // true
newStr instanceof String; // true
objStr instanceof Object; // true
myNonObj instanceof Object; // false,一种创建非Object实例的对象的方法
aDate instanceof Date; // true
aDate instanceof Object; // true
Object.prototype.toString.call()优点:精准判断数据类型,所有原始数据类型都是能判断;缺点:写法繁琐,最好进行封装后使用
var toString = Object.prototype.toString;
console.log(toString.call(55)); // [object Number]
console.log(toString.call(true)); // [object Boolean]
console.log(toString.call('aa')); // [object String]
console.log(toString.call([])); // [object Array]
console.log(toString.call(function(){})); // [object Function]
console.log(toString.call({})); // [object Object]
console.log(toString.call(undefined)); // [object Undefined]
console.log(toString.call(null)); // [object Null]
console.log(toString.call(Math)); // [object Math]
console.log(toString.call(Set)); // [object Function] Set构造函数
console.log(toString.call(Array)); // [object Function] Array构造函数
console.log(toString.call(Map)); // [object Function]
console.log(toString.call(Date)); // [object Function]
console.log(toString.call(new Set())); // [object Set]
console.log(toString.call(new Array())); // [object Array]
console.log(toString.call(new Map())); // [object Map]
console.log(toString.call(new Date())); // [object Date]
function D(){
}
console.log(toString.call(D)); // [object Function]
console.log(toString.call(new D())); // [object Object]
如何判断变量是否为数组?let arr = []
console.log(Array.isArray(arr)); // true
arr.__proto__ === Array.prototype; // true
arr instanceof Array; // true
Object.prototype.toString.call(arr); // [object Array]
判断是否是Promise对象
function isPromise(val) {
return (typeof val.then === 'function' && typeof val.catch === 'function')
}
let p = new Promise((resolve, reject) => {});
console.log(isPromise(p)); // true