Why does typeof array with objects return "object" and not "array"? [duplicate]
Possible Duplicate:
JavaScript: Check if object is array?
Why is an array of objects considered an object, and not an array? For example:
$.ajax({
url: 'http://api.twitter.com/1/statuses/user_timeline.json',
data: { screen_name: 'mick__romney'},
dataType: 'jsonp',
success: function(data) {
console.dir(data); //Array[20]
alert(typeof data); //Object
}
});
Fiddle
One of the weird behaviour and spec in Javascript is the typeof Array is Object
.
You can check if the variable is an array in couple of ways:
var isArr = data instanceof Array;
var isArr = Array.isArray(data);
But the most reliable way is:
isArr = Object.prototype.toString.call(data) == '[object Array]';
Since you tagged your question with jQuery, you can use jQuery isArray
function:
var isArr = $.isArray(data);
Quoting the spec
15.4 Array Objects
Array objects give special treatment to a certain class of property names. A property name P (in the form of a String value) is an array index if and only if ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal to 2^32-1. A property whose property name is an array index is also called an element. Every Array object has a length property whose value is always a nonnegative integer less than 2^32. The value of the length property is numerically greater than the name of every property whose name is an array index; whenever a property of an Array object is created or changed, other properties are adjusted as necessary to maintain this invariant. Specifically, whenever a property is added whose name is an array index, the length property is changed, if necessary, to be one more than the numeric value of that array index; and whenever the length property is changed, every property whose name is an array index whose value is not smaller than the new length is automatically deleted. This constraint applies only to own properties of an Array object and is unaffected by length or array index properties that may be inherited from its prototypes.
And here's a table for typeof
To add some background, there are two data types in JavaScript:
- Primitive Data types - This includes null, undefined, string, boolean, number and object.
- Derived data types/Special Objects - These include functions, arrays and regular expressions. And yes, these are all derived from "Object" in JavaScript.
An object in JavaScript is similar in structure to the associative array/dictionary seen in most object oriented languages - i.e., it has a set of key-value pairs.
An array can be considered to be an object with the following properties/keys:
- Length - This can be 0 or above (non-negative).
- The array indices. By this, I mean "0", "1", "2", etc are all properties of array object.
Hope this helped shed more light on why typeof Array returns an object. Cheers!