最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - typeof something return object instead of array - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question edited Jan 28, 2016 at 9:22 Charlie 23.8k12 gold badges63 silver badges95 bronze badges asked Jan 28, 2016 at 7:27 Jennifer Jennifer 9059 silver badges21 bronze badges 4
  • When do you initialize your 'x' ? – Alteyss Commented Jan 28, 2016 at 7:27
  • Because array is of type object – Rayon Commented Jan 28, 2016 at 7:30
  • 4 Possible duplicate of Check if object is array? – hjpotter92 Commented Jan 28, 2016 at 7:30
  • You should watch out for examples for typeof – Shubh Commented Jan 28, 2016 at 7:31
Add a comment  | 

7 Answers 7

Reset to default 6

Arrays are objects in JS.

If you need to test a variable for array:

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

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

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

Array is an Object type, so it's fine !

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
  }
}
发布评论

评论列表(0)

  1. 暂无评论