Home > Web Front-end > JS Tutorial > Why does `typeof` return \'object\' for arrays of objects in JavaScript?

Why does `typeof` return \'object\' for arrays of objects in JavaScript?

Mary-Kate Olsen
Release: 2024-11-02 20:12:02
Original
911 people have browsed it

Why does `typeof` return

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
    }
});​
Copy after login

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:

  • instanceof Array: Checks if a variable is an instance of the Array constructor.
  • Array.isArray(data): A native method specifically designed to determine if a variable is an array.
  • Object.prototype.toString.call(data) == '[object Array]': A reliable approach that utilizes the toString method of the Object prototype.
  • jQuery.isArray(data): A convenient option for jQuery users.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template