本文介绍了为什么使用对象的typeof数组返回"对象"而不是"数组"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:结果
为什么对象的数组考虑的对象,而不是一个数组?例如:
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
}
});
推荐答案
一个JavaScript中的怪异行为和规范的是将typeof数组是对象
。
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]';
由于您使用jQuery标记你的问题,你可以使用jQuery 功能:
var isArr = $.isArray(data);
这篇关于为什么使用对象的typeof数组返回"对象"而不是"数组"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!