简体   繁体   中英

typeof something return object instead of array

x is an array.

I do console.log(x) I got

[ 'value' ]

but when I check the x with type of like console.log(typeof x) it says it's an Object. Why?

Arrays are objects in JS.

If you need to test a variable for array:

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

if your purpose is to check, the "is it Array or not" ? you better use

Array.isArray()

The Array.isArray() method returns true if an object is an array, false if it is not. LINK

so you can try

if(typeof x === 'object' &&  Array.isArray(x)) {
    //Its an array
}

UPDATE: Array is an object, so typeof x reports its an object. but then why on earth typeof function reports it correctly!!! ? Good question . take good care while using typeof

According to MDN, there is no array type in javascript when using typeof There is only object.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof

数组是对象类型,所以没问题!

X is an Array defined in global scope. So, when you do console.log(x), you are able to see

 ['value']

Also, refer here for details about JavaScript data types which says,

Arrays are regular objects for which there is a particular relationship between integer-key-ed properties and the 'length' property

Hence the type return as Object is correct and as expected.

there isn't "Array" type in javascript

 typeof ['1'];//object
 typeof {};//object
 typeof null;//object

other often used value type:

 number,string,undefined,boolean,function

The typeof operator threw me off a couple times before I discovered that arrays, null, and objects will all return as 'object'. I threw together this quick and dirty function that I now use in place of typeof - which still returns a string indicating the variable type:

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
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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