x
是一个数组。
当我执行 console.log(x)
时,我得到了:
[ 'value' ]
但是当我用类似于console.log(typeof x)
的方式检查x的类型时,它会显示为一个对象。为什么?
x
是一个数组。
当我执行 console.log(x)
时,我得到了:
[ 'value' ]
但是当我用类似于console.log(typeof x)
的方式检查x的类型时,它会显示为一个对象。为什么?
在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 function
正确报告它呢!!!?这是个好问题。在使用typeof
时要小心。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof
typeof
并不总是返回数据类型。对于 function(){ }
,它将返回 function
,但实际上并不存在 function
这个数据类型。 - RayonX 是在全局范围内定义的数组。因此,当您执行 console.log(x) 时,您可以看到
['value']
此外,有关 JavaScript 数据类型的详细信息,请参见此处,其中提到:
数组是常规对象,整数键属性和“length”属性之间存在特殊关系
因此,返回类型Object是正确且符合预期的。
JavaScript 中没有 "Array" 类型
typeof ['1'];//object
typeof {};//object
typeof null;//object
其他常用的值类型:
number,string,undefined,boolean,function
typeof 运算符在我发现数组、null 和对象都会返回 'object' 之前曾经让我困扰了几次。我写了这个快速而简单的函数来代替 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
}
}
数组是一个对象类型,所以没问题!
array
的类型是object
。 - Rayontypeof
的用例。 - Shubh