JavaScript property constructor does not work.

Any property of a Constructor object returns its constructor function, but it does not work for an array.

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

Any idea?

+4
source share
1 answer

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

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

The proposed workaround a.length will not work 100%, because it is possible to have an object with the length property without an actual array.

+1
source

Source: https://habr.com/ru/post/1439460/


All Articles