0

When I do: typeof([]) it returns object.

I've heard its not really acceptable to edit the prototypes of JavaScript's inbuilt types.

However, if I do this: Array.prototype.isArray = true; and then the following work:

var arr = [];
var obj = {};

if (arr.isArray)
{
    console.log("Array");
}
else
{
    console.log("Not array");
}

if (obj.isArray) // undefined
{
    console.log("Array");
}
else
{
    console.log("Not array");
}

Or is this still not acceptable? What would be a better way around this?

Cheetah
  • 13,785
  • 31
  • 106
  • 190

2 Answers2

0

You could use

yourThing.constructor === Array

This returns true if yourThing is an array.

So you don't have to change Array's prototype. Modifying objects you don't own is widely seen as bad practice.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
0

You can use instanceof (MDN Documentation) :

var arr = [];
if (arr instanceof Array) {
  console.log('this is an array');
}
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
Elorfin
  • 2,487
  • 1
  • 27
  • 50