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
andb === 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
4 Answers
Reset to default 4This 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.
- Array.isArray(variableName)
- variableName instanceof Array
- 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
版权声明:本文标题:javascript - how to differentiate between object and array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744321642a2600528.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论