如何判断一个值为对象类型
- 使用typeof判断(不推荐);
let a = {}; typeof a; //object let a = []; typeof a;//object let a = null; typeof a;//object
缺点是:使用typeof时,数组和null判断结果都为对象类型所以不推荐
- 使用instanceof判断;
let a = []; a instanceof Object;//true let a = {}; a instanceof Object;//true
缺点是:使用instanceof时,数组也为对象类型
- 使用JSON.stringify()判断(推荐);
let a = {}; JSON.stringify(a) == "{}";//true
- 使用Object.prototype.toString.call()判断(推荐);
Object.prototype.toString.call(null) '[object Null]'
Object.prototype.toString.call({}) '[object Object]'
Object.prototype.toString.call([]) '[object Array]'
Object.prototype.toString.call("") '[object String]'
Object.prototype.toString.call(undefined) '[object Undefined]'
Object.prototype.toString.call(false)
'[object Boolean]'