Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
156
rated 0 times [  158] [ 2]  / answers: 1 / hits: 191306  / 12 Years ago, sun, october 21, 2012, 12:00:00

Possible Duplicate:

JavaScript: Check if object is array?






Why is an array of objects considered an object, and not an array? For example:



$.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
}
});​


Fiddle


More From » jquery

 Answers
5

One of the weird behaviour and spec in Javascript is the typeof Array is Object.



You can check if the variable is an array in couple of ways:



var isArr = data instanceof Array;
var isArr = Array.isArray(data);


But the most reliable way is:



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


Since you tagged your question with jQuery, you can use jQuery isArray function:



var isArr = $.isArray(data);

[#82449] Friday, October 19, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
hasanb

Total Points: 321
Total Questions: 102
Total Answers: 96

Location: Burkina Faso
Member since Fri, Sep 4, 2020
4 Years ago
;