In JavaScript how to detect weather the type is Array or Object? [duplicate]
Asked Answered
I

1

8

I need to know how to check the variable if its an Array or its an Object

var arr = ['foo', 'bar'];
var obj = {
  0: 'foo',
  1: 'bar'
}

document.write('arr is an: ' + typeof arr + ', obj is an: ' + typeof obj)

// The result is always:
// arr is an: object, obj is an: object

Is there any way to tell the difference between the two types?

It answered 23/2, 2016 at 13:10 Comment(0)
C
2

Array.isArray(arr) will return true. Array.isArray(obj) will return false.

Callender answered 23/2, 2016 at 13:11 Comment(1)
Thanks that was really helpfulIt

© 2022 - 2024 — McMap. All rights reserved.