Вопрос

Alright, so nothing fancy here, just some JSON:

var a = ["foo", "bar", "baz"];

var o = {a: "foo", b: "bar", c: "baz"};

But what happens when we do this?

typeof a; // => "object"

I'd like it if I could just get that command to say "array". But I can't. Is there any way to differentiate?

Это было полезно?

Решение

You can check if the object is an instance of Array:

var isArray = a instanceof Array;

Другие советы

Use the instanceof operator.

if (a instanceof Array)

Keep in mind that all Arrays are Objects (as Object is on Array's prototype chain), so to distinguish between an Array and a not-Array you have to compare to the Array constructor, you can't use the Object constructor for this.

If you're not in a multi window environment, you can either check the constructor...

var isArray = possiblyAnArray.constructor == Array;

...or use instanceof...

var isArray = possiblyAnArray instanceof Array;

These won't work in a multi window environment, as the Array constructor of a different window will hold a different reference. In that case, you'd need to do it a slower way...

var isArray = ({}).toString.call(possiblyAnArray) == "[object Array]";

I've seen another method too, which is very easy to implement but not at all guaranteed to strictly tell you what's an Array or not.

Array.prototype.isArray = true;
var isArray = [].isArray;

I don't recommend using that, but it's interesting to see how it works.

Another approach would to use duck typing. It's depends on the use case.

If, for instance, you want to count the items in the array, which is not something you can do in the JSON Object, you can try:

if (typeof(obj.length) !=="undefined"){ //do whatever}

This will give you the option to base your code on the objects attributes, rather than on it's real class, which might be less relevant in some cases.

Just found this: is there anything wrong with it?

var a = [4,5,6,7];
if(typeof a === object) a.type = "object";
if(a.__proto__ === Array.prototype) a.type = "array";
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top