3

Why is this line of javascript not creating an instance of the array prototype? (The var I am interested in is formatSet)

var date = angular.copy(srcDate),
    d = '',
    yyyy = date.getFullYear() - 2,
    MM = date.getMonth() + 1,
    dd = date.getDate(),
    hh = date.getHours(),
    mm = date.getMinutes(),
    ss = date.getSeconds(),
    formatSet = [MM, dd, hh, mm, ss];

Forgive me if this is a duplicate, but the search terms are a little vague and everything I'm finding illustrates the use of Array.prototype.isArray(), with which I am familiar and still doesn't answer the question.

Also, in case I'm missing something, the scenario that arises are errors: formatSet.isArray and formatSet.forEach is not a function.

Kraken
  • 5,043
  • 3
  • 25
  • 46
  • 2
    I don't know `isArray()` but from a bit of reading it looks to not be broadly implemented. If I use your above code and change the first line to `var date = new Date(),` then formatSet is an array and has the other expected functions available (forEach, for example). So, what's the date variable after you run that line of code? – Reinstate Monica Cellio Apr 26 '16 at 16:22
  • Okay - after that change this also works... `Array.isArray(formatSet);` - returns true. – Reinstate Monica Cellio Apr 26 '16 at 16:25

2 Answers2

3

You need to do:

Array.isArray(formatSet);

Instead of:

formatSet.isArray();
Jamie
  • 467
  • 8
  • 19
0

The best way to check if is array is like this:

if (formatSet.constructor === Array )

This is the fastest method.

Array.isArray() doesn’t always benchmark well.

check this for more details:

How do you check if a variable is an array in JavaScript?

Community
  • 1
  • 1
Hugo S. Mendes
  • 1,076
  • 11
  • 23