为什么类型的数组与对象返回“对象”而不是“数组”?(Why does typeof array with objects return “object” and not “array”? [duplicate])
可能重复: JavaScript:检查对象是否是数组?
为什么一组对象被认为是一个对象,而不是一个数组? 例如:
$.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 } });小提琴
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
最满意答案
Javascript中的一个奇怪的行为和规范是Array的Object 。
您可以通过几种方式检查变量是否为数组:
var isArr = data instanceof Array; var isArr = Array.isArray(data);但最可靠的方法是:
isArr = Object.prototype.toString.call(data) == '[object Array]';由于您使用jQuery标记了您的问题,您可以使用jQuery isArray函数:
var isArr = $.isArray(data);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);更多推荐
发布评论