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:
$.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
}
});
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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3