可能的重复:
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
}
});
小提琴
Javascript中一个奇怪的行为和规范是typeof Array is 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);
引用说明书
15.4数组对象
Array objects give special treatment to a certain class of property names. A property name P (in the form of a String value) is an array index if and only if ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal to 2^32-1. A property whose property name is an array index is also called an element. Every Array object has a length property whose value is always a nonnegative integer less than 2^32. The value of the length property is numerically greater than the name of every property whose name is an array index; whenever a property of an Array object is created or changed, other properties are adjusted as necessary to maintain this invariant. Specifically, whenever a property is added whose name is an array index, the length property is changed, if necessary, to be one more than the numeric value of that array index; and whenever the length property is changed, every property whose name is an array index whose value is not smaller than the new length is automatically deleted. This constraint applies only to own properties of an Array object and is unaffected by length or array index properties that may be inherited from its prototypes.
这是typeof的表格
添加一些背景信息,JavaScript中有两种数据类型:
基本数据类型-这包括空,未定义,字符串,布尔,数字和对象。
派生数据类型/特殊对象——包括函数、数组和正则表达式。是的,这些都源自JavaScript中的“Object”。
JavaScript中的对象在结构上类似于大多数面向对象语言中的关联数组/字典——也就是说,它有一组键值对。
数组可以被认为是一个具有以下属性/键的对象:
长度——可以是0或以上(非负)。
数组下标。我的意思是,“0”、“1”、“2”等都是数组对象的属性。
希望这有助于阐明typeof Array返回对象的原因。干杯!
试试这个例子,你也会明白JavaScript中关联数组和对象的区别。
关联数组
var a = new Array(1,2,3);
a['key'] = 'experiment';
Array.isArray(a);
返回true
请记住,a.length将是未定义的,因为length被视为键,您应该使用Object.keys(a)。获取关联数组的长度。
对象
var a = {1:1, 2:2, 3:3,'key':'experiment'};
Array.isArray(a)
返回false
JSON返回Object…可以返回一个关联数组…但事实并非如此