"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why Does `typeof` Return \"Object\" for Arrays Containing Objects in JavaScript?

Why Does `typeof` Return \"Object\" for Arrays Containing Objects in JavaScript?

Published on 2024-11-08
Browse:918

Why Does `typeof` Return \

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:

  • data instanceof Array: Checks if the variable is an instance of the Array type.
  • Array.isArray(data): A method specifically designed to determine if an object is an array.
  • Object.prototype.toString.call(data) == '[object Array]': A reliable and widely accepted method for array detection.
  • $.isArray(data): A jQuery-specific function designed to check for arrays.

By understanding this peculiarity and utilizing these techniques, developers can effectively handle arrays of objects in their JavaScript code.

Latest tutorial More>

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