简体   繁体   中英

how to differentiate between object and array

let a = {}
let b = []

typeof a // returns an object
typeof b // returns an object

 a === {} // false
 b === [] // false
 a === b // false

how then can I know if its an array or object, I'm trying to validate user input, where it can either be an array or object but in either Case I don't want the value to be empty

This is really a few questions wrapped up into one. First off, it is counter-intuitive for many that typeof [] is 'object' . This is simply because an Array is an reference type ( null , Date instances, and any other object references also have typeof of object ).

Thankfully, to know if an object is an instance of Array , you can now use the convenient Array.isArray(...) function. Alternatively, and you can use this for any type of object, you can do something like b instanceof Array .

Knowing if one of these is empty can be done by checking Object.keys(a).length === 0 , though for Arrays it's more natural to do b.length === 0 .

Checking any two objects variables (including Arrays) with === will only tell you if the two variables reference the same object in memory, not if their contents are equal.

Since both Arrays and Objects share the same type, you can check for instance:

if (b instanceof Array) {

}
if (Array.isArray(a) && a.length === 0) {
  // a is an array and an empty one
}

Actually, using typeof for both Objects and Arrays will return Object . There are certain methods in JS to check if a variable is an array or not.

  1. Array.isArray(variableName)
  2. variableName instanceof Array
  3. variableName.constructor === Array

All these Methods will return true if variable is an array else will return false .

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