Examination of the Unique JavaScript Behavior: Why Arrays of Objects Return "object" Instead of "array"
In JavaScript, an intriguing phenomenon arises when working with arrays of objects. Surprisingly, despite their array-like nature, they are classified as objects when the typeof operator is employed. This discrepancy can be quite perplexing, especially in cases like the below:
$.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 } });
This behavior stems from a peculiarity in the JavaScript specification that considers Array objects to be of type Object. However, this does not imply that arrays and objects are interchangeable. To accurately determine whether a variable represents an array, employ the following methods:
By utilizing these techniques, you can precisely discern whether a variable is an array, even when it contains objects, resolving the apparent discrepancy between its array-like behavior and object classification.
The above is the detailed content of Why does `typeof` return \'object\' for arrays of objects in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!