4

Any object Constructor property return its constructor function, but it doesnt work for Array.

var o={};
o.constructor; --> returns Object()

var a=new Array();
a.constructor; --> Expecting Array() but it returns [undefined]

Any idea?

j08691
  • 204,283
  • 31
  • 260
  • 272
Kac
  • 51
  • 8
  • 4
    Actually in Chrome and IE both versions return a function. What is the underlying problem you're trying to solve? – Wolfgang Stengel Oct 12 '12 at 19:00
  • I am trying to detect whether its an array or not though we have other workaround (a.length>0).. – Kac Oct 12 '12 at 19:28
  • 3
    Uh, `your_object instanceof Array`? Better, isn't it? – F.X. Oct 12 '12 at 19:39
  • To check if an object is an array you can use `Object.prototype.toString.call(your_object) == '[object Array]'` – krcko Oct 12 '12 at 19:59
  • More detail here: http://stackoverflow.com/questions/4775722/javascript-check-if-object-is-array – Wolfgang Stengel Oct 12 '12 at 20:22
  • Be careful with constructor : it will throws a TypeError if your object is null. As explain in this good article on types checking : http://tobyho.com/2011/01/28/checking-types-in-javascript/ – greg Oct 12 '12 at 20:23

1 Answers1

1

The constructor property of an object will refer to a function. Instead to check if a variable holds an array, do this:

if (Object.prototype.toString.call(a)==='[object Array]') alert('Array!');

The proposed a.length workaround will not work 100 % because it's possible to have an object that has the length property without being an actual array.

Wolfgang Stengel
  • 2,867
  • 1
  • 17
  • 22
  • cool. yeah you are correct. ".length" property works with the other object. thanks for ur time. – Kac Oct 12 '12 at 22:45