简体   繁体   English

如何区分对象和数组

[英]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' .首先,对于许多人来说typeof []'object'是违反直觉的。 This is simply because an Array is an reference type ( null , Date instances, and any other object references also have typeof of object ).这仅仅是因为 Array 是一种引用类型( nullDate实例和任何其他 object 引用的typeof也为object )。

Thankfully, to know if an object is an instance of Array , you can now use the convenient Array.isArray(...) function.幸运的是,要知道 object 是否是Array的实例,您现在可以使用方便的Array.isArray(...) function。 Alternatively, and you can use this for any type of object, you can do something like b instanceof Array .或者,您可以将其用于任何类型的 object,您可以执行类似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 .可以通过检查Object.keys(a).length === 0来了解其中一个是否为,尽管对于 Arrays 来说更自然的是做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.使用===检查任何两个对象变量(包括数组)只会告诉您这两个变量是否引用 memory 中的相同 object,而不是它们的内容是否相等。

Since both Arrays and Objects share the same type, you can check for instance:由于 Arrays 和 Objects 共享相同的类型,您可以检查例如:

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 .实际上,对对象和数组使用typeof将返回Object There are certain methods in JS to check if a variable is an array or not. JS 中有一些方法可以检查变量是否为数组。

  1. Array.isArray(variableName) Array.isArray(变量名)
  2. variableName instanceof Array变量名 instanceof 数组
  3. variableName.constructor === Array variableName.constructor === 数组

All these Methods will return true if variable is an array else will return false .如果变量是数组,所有这些方法都将返回true ,否则将返回false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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