简体   繁体   中英

How to validate it must be an object?

Is it necessary two use two conditions to check if data is an object otherwise throw an error?

if (typeof data !== "object" || Array.isArray(data)) {
    throw new Error(`data is not an object`);
}

It appear typeof data !== "object" treated as array as well.

To achieve expected result, use below option of verifying whether data is object or array by constructor name

In Javascript, there is no separate data type for array and they are list-like objects

As per MDN- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

The JavaScript Array object is a global object that is used in the construction of arrays; which are high-level, list-like objects.

Refer this link for more details - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor

 var data1 = [1,2,3] var data2= { a:1, b:2 } var data3= Object.create(null) var data4= null; console.log("data1-type", data1.constructor && data1.constructor.name || typeof data1) console.log("data2-type", data2.constructor && data2.constructor.name || typeof data2) console.log("data3-type", data3.constructor && data3.constructor.name || typeof data3) console.log("data4-type", data4 && data4.constructor && data4.constructor.name || typeof data4) 

In addition to a regular object, both null and Array will also have typeof as "object" so if you're trying to make sure it's only a regular object and not null or Array , then you would just add one more check to what you already had:

if (!data || typeof data !== "object" || Array.isArray(data)) {
    throw new Error(`data is not an object`);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM