admin管理员组

文章数量:1401628

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

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

Share Improve this question edited Oct 1, 2022 at 14:25 Chukwuemeka Maduekwe asked May 10, 2020 at 23:42 Chukwuemeka MaduekweChukwuemeka Maduekwe 8,6367 gold badges60 silver badges75 bronze badges 1
  • 2 Both a === a and b === b are actually true; perhaps you meant that {} === {} and [] === [] are both false (which is expected since === does an object reference parison, and {} and [] both create new objects) – Jacob Commented May 10, 2020 at 23:45
Add a ment  | 

4 Answers 4

Reset to default 4

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.

本文标签: javascripthow to differentiate between object and arrayStack Overflow