Javascript 返回对象而不是数组的类型

Javascript 返回对象而不是数组的类型,javascript,jquery,Javascript,Jquery,x是一个数组 我有console.log(x) [ 'value' ] 但是,当我用type of likeconsole.log(typeof x)检查x时,它说它是一个对象。为什么?数组是一种对象类型,所以它很好 根据MDN,当使用typeof时,javascript中没有数组类型 只有一个目标 数组是JS中的对象 如果需要测试数组的变量,请执行以下操作: if (x.constructor === Array) console.log('its an array'); 如果您的目

x
是一个数组

我有
console.log(x)

[ 'value' ]

但是,当我用type of like
console.log(typeof x)
检查x时,它说它是一个对象。为什么?

数组是一种对象类型,所以它很好

根据MDN,当使用typeof时,javascript中没有数组类型 只有一个目标


数组是JS中的对象

如果需要测试数组的变量,请执行以下操作:

if (x.constructor === Array)
   console.log('its an array');

如果您的目的是检查,“是否为数组”?你最好用

Array.isArray()
如果对象是数组,则Array.isArray()方法返回true;如果对象不是数组,则返回false

所以你可以试试

if(typeof x === 'object' &&  Array.isArray(x)) {
    //Its an array
}
更新:
数组是一个对象,因此
typeof x
报告它是一个对象。但是,究竟为什么
函数类型
正确地报告了它好问题在使用
typeof

X是在全局范围内定义的数组。因此,当您执行console.log(x)时,您可以看到

 ['value']
另外,有关JavaScript数据类型的详细信息,请参见

数组是常规对象,其整数键属性和“length”属性之间存在特定关系

因此,返回为对象的类型是正确的,正如预期的那样。

javascript中没有“Array”类型

 typeof ['1'];//object
 typeof {};//object
 typeof null;//object
其他常用值类型:

 number,string,undefined,boolean,function

在我发现数组、null和对象都将以“object”的形式返回之前,typeof操作符让我犹豫了好几次。我拼凑了这个快速而肮脏的函数,现在我用它来代替typeof,它仍然返回一个字符串,指示变量类型:

TestType = (variable) => {
  if(Array.isArray(variable)){
    return 'array'
  }
  else if(variable === null){ //make sure to use the triple equals sign (===) as a double equals sign (==) will also return null if the variable is undefined
    return 'null'
  }else{
    return typeof variable
  }
}

什么时候初始化“x”?因为
array
的类型是
object
可能的重复,您应该注意
typeof
也不总是返回数据类型的示例。..for
function(){}
它将返回
函数
,但没有数据类型为
函数
。第一次看到这个!