What's Happening: "Object" Type for Arrays of Objects
In JavaScript, an unexpected phenomenon occurs when an array contains objects. Instead of being classified as an "array," it is labeled as an "object." This behavior becomes evident in situations like the one illustrated below:
<code class="javascript">$.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 } }); </code>
Why the Confusion?
The reason behind this peculiar behavior lies in JavaScript's仕様. By default, Array is considered an "object" type, even though it represents an ordered list of values. This means that all arrays, including those containing objects, inherit the properties and functionality of the Object type.
Identifying Arrays
To determine whether a variable is an actual array, several approaches can be taken:
<code class="javascript">var isArr = data instanceof Array; var isArr = Array.isArray(data);</code>
However, the most dependable method involves examining the variable's prototype chain:
<code class="javascript">isArr = Object.prototype.toString.call(data) == '[object Array]';</code>
Using jQuery
For those utilizing jQuery, a dedicated isArray function is available:
<code class="javascript">var isArr = $.isArray(data);</code>
By employing these methods, developers can accurately categorize variables as arrays, even when they contain objects, ensuring proper handling and manipulation of their data.
The above is the detailed content of Why is an Array of Objects Considered an \'Object\' in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!