Home >Web Front-end >JS Tutorial >Why Does `typeof` Return \'Object\' for Arrays Containing Objects in JavaScript?
Understanding the Contradiction: Why typeof Array with Objects Returns "Object"
Developers may encounter a surprising phenomenon: when invoking typeof on an array containing objects, it inexplicably returns "object" instead of "array." This article delves into this seemingly contradictory behavior.
By examining an example, let's illustrate the issue:
<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>
While console.dir(data) correctly identifies the variable as an array, typeof data incongruously returns "Object."
The explanation lies in JavaScript's peculiar specification, where the typeof operator returns the type of the object's internal [[Class]] property. In the case of arrays, their [[Class]] property is set to "Array," but when surrounded by objects, the [[Class]] property changes to "Object."
To ensure accurate type checking, developers can employ various approaches:
By understanding this peculiarity and utilizing these techniques, developers can effectively handle arrays of objects in their JavaScript code.
The above is the detailed content of Why Does `typeof` Return \'Object\' for Arrays Containing Objects in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!