js空对象判断 isPlainObject

//有缺陷,JSON.stringify(obj)中,如果obj本来是空的,又继承了一个非空的对象那么结果也会是“{}”
1. JSON.stringify(obj) == '{}' 

2. Object.keys(obj).length == 0 

//错误,当对象为空Array,length为1,空arguments时,length为2
//具体参考https://github.com/arasatasaygin/is.js/blob/master/is.js
3. Object.getOwnPropertyNames(value).length == 0 

4. 一个完备的方法

//出自https://github.com/sindresorhus/is/blob/master/source/index.ts

function isPlainObject(obj){
    let prototype;

    return Object.prototype.toString.call(obj) === '[object Object]' 
        && (prototype = Object.getPrototypeOf(obj), prototype === null || 
        prototype == Object.getPrototypeOf({}))
}
原文地址:https://www.cnblogs.com/mengff/p/9693284.html