确定某个对象在JavaScript中是否为普通对象的方法
我最近偶然发现了这个函数,它确定某个对象是否是纯对象,即JavaScript:确定某个对象在JavaScript中是否为普通对象的方法,javascript,object,Javascript,Object,我最近偶然发现了这个函数,它确定某个对象是否是纯对象,即JavaScript: function isPlainObject (value){ if (typeof value !== 'object' || value === null) return false; let proto = value; while (Object.getPrototypeOf(proto) !== null) { proto = Object.getPrototypeOf(proto);
function isPlainObject (value){
if (typeof value !== 'object' || value === null) return false;
let proto = value;
while (Object.getPrototypeOf(proto) !== null) {
proto = Object.getPrototypeOf(proto);
}
return Object.getPrototypeOf(value) === proto;
};
资料来源:
我想知道:
对象。原型是对象。不,它执行不必要的操作
const isPlainObj = value => !!value &&
Object.getPrototypeOf(value) === Object.prototype;
如果您只想知道value
prototype是Object,那么就不必太花哨了。prototype
在其“Obj”模块下有一个方法,可以检查对象是否实际上是普通对象文本
参考:
在其上或通过其获取代码,并按如下所示使用
// export the methods in the "Obj" module
var $ = ToolJS.export("Obj");
var myObj = {name: "John Doe"};
var myArr = [1,2,3]; // note that arrays are of type object but are obviously not plain objects
var myEl = document.getElementById("elem"); // elements are also objects
$.isObj(myObj); // => true
$.isObj(myArr); // => false
$.isObj(myEl); // => false
你可以查看它的完整文档
在后台,该方法检查项类型是否为null或未定义,而是一个对象,然后检查其构造函数以查看其是否为对象,然后确保其不是数组,最后将其转换为字符串以查看其是否为普通对象。
object.prototype.toString.call(value)
返回[object-object]
当值
是普通对象时。
// export the methods in the "Obj" module
var $ = ToolJS.export("Obj");
var myObj = {name: "John Doe"};
var myArr = [1,2,3]; // note that arrays are of type object but are obviously not plain objects
var myEl = document.getElementById("elem"); // elements are also objects
$.isObj(myObj); // => true
$.isObj(myArr); // => false
$.isObj(myEl); // => false