为什么类型的数组与对象返回“对象”而不是“数组”?(Why does typeof array with objects return “object” and not “array”? [dupli

编程入门 行业动态 更新时间:2024-10-27 16:37:21
为什么类型的数组与对象返回“对象”而不是“数组”?(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);

更多推荐

本文发布于:2023-07-15 11:03:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1112854.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   对象   而不是   类型   typeof

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!