jQuery对象如何模仿数组? [英] How do jQuery objects imitate arrays?

查看:90
本文介绍了jQuery对象如何模仿数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jQuery对象就像数组一样,不会污染原生原型。
这是如何实现的?

jQuery objects act like arrays without polluting native prototypes. How is this achieved?

我知道它不仅仅是带有数字键的对象 - 所以也许只是提供相应的方法(类似 jQuery.prototype.indexOf = Array.prototype.indexOf )。

I know it's not just objects with numeric keys - so perhaps it's just a matter of providing the respective methods (something like jQuery.prototype.indexOf = Array.prototype.indexOf).

我用Google搜索并查看了源代码,但是找不到确定的答案。

I've googled and looked at the source, but couldn't find a definitive answer.

推荐答案

虽然jQuery对象就像数组一样,但它们实际上只是 array-like 对象。类数组对象是一个使用数字键且具有长度属性的对象 - 这是与原生数组方法

Although jQuery objects act like arrays, they are actually only array-like objects. An array-like object is an object using numeric keys and having a length property - that is the minimum needed for compatibility with the native array methods.

因为jQuery对象只是类似数组而不是实际的 Array 对象,本机数组操作(如 indexOf 反向 )不能直接打电话。您可以使用 Array.prototype ,或者扩展jQuery的功能。

Because jQuery objects are only array-like and not actual Array objects, native array operations (like indexOf or reverse) cannot be called directly. You can use Array.prototype though, or extend jQuery's functionality.

$('div').reverse(); // TypeError: $("div").reverse is not a function

// we can use Array.prototype though
Array.prototype.reverse.apply($('div'));

// or we can extend jQuery very easily
$.fn.reverse = Array.prototype.reverse;
$('div').reverse(); // now it works!

您认为Firebug不包含任何用于格式化jQuery对象的特殊外壳是正确的。快速搜索会在Firebug邮件列表中显示相关帖子。假设信息仍然正确(帖子是从1月开始),如果对象具有有限长度 splice 方法

You are correct in your assumption that Firebug does not include any special-casing for formatting jQuery objects. A quick search reveals a relevant post on the Firebug mailing list. Assuming the information is still correct (the post is from January) Firebug will format an object as an array if it has a finite length and a splice method.

JQuery满足这两个条件,但他们对 splice 的实现只不过是本机<$的直接副本c $ c>数组方法。它没有文档,这意味着它只是为了内部使用,或者可能只是为了欺骗Firebug很好地格式化jQuery对象。

JQuery fulfils both of these criteria, but their implementation of splice is nothing more than a direct copy of the native Array method. It is undocumented, which means it's either only for internal use, or perhaps added solely for the purpose of tricking Firebug into formatting jQuery objects nicely.

这篇关于jQuery对象如何模仿数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆