Home > Web Front-end > JS Tutorial > body text

Why Does `typeof` Return \'Object\' for JavaScript Arrays?

Mary-Kate Olsen
Release: 2024-11-02 19:18:31
Original
648 people have browsed it

Why Does `typeof` Return

Understanding Array Type in JavaScript: Why Does typeof Return "Object" Instead of "Array"?

JavaScript exhibits an intriguing behavior where the typeof operator returns "object" for an array of objects. This can be observed in scenarios such as the following code:

$.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

In the above code, data is an array of objects representing Twitter statuses. While console.dir() reports that the type is "Array", typeof returns "Object".

This behavior stems from the fact that JavaScript Arrays are technically objects. They inherit from the Object prototype, which means that they possess object-like properties and methods. This inheritance is responsible for the "Object" result from typeof.

To determine if a variable is truly an array in JavaScript, there are several reliable methods:

1. instanceof Operator:

var isArr = data instanceof Array;
Copy after login

2. Array.isArray() Method:

var isArr = Array.isArray(data);
Copy after login

3. Object.prototype.toString.call() Method:

isArr = Object.prototype.toString.call(data) == '[object Array]';
Copy after login

4. jQuery isArray() Function (if using jQuery):

var isArr = $.isArray(data);
Copy after login

These methods offer more accurate results than typeof when distinguishing between arrays and other types of objects. By leveraging these alternatives, developers can confidently work with arrays in JavaScript without the confusion caused by the typeof behavior.

The above is the detailed content of Why Does `typeof` Return \'Object\' for JavaScript Arrays?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!