jQuery对象如何模仿数组?

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

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

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

虽然jQuery对象就像数组一样,但它们实际上只是类似于数组的对象。 类数组对象是使用数字键并具有length属性的对象 – 这是与本机数组方法兼容所需的最小值。

因为jQuery对象只是类似数组而不是实际的Array对象,所以不能直接调用本机数组操作(如indexOfreverse )。 您可以使用Array.prototype ,或者扩展jQuery的function。

 $('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对象的任何特殊shell,这是正确的。 快速搜索显示Firebug邮件列表中的相关post 。 假设信息仍然正确(post是从1月开始),Firebug会将对象格式化为数组(如果它具有有限长度splice方法)

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

查看jquery代码(开发),第139行:

 // Force the current matched set of elements to become // the specified array of elements (destroying the stack in the process) // You should use pushStack() in order to do this, but maintain the stack setArray: function( elems ) { // Resetting the length to 0, then using the native Array push // is a super-fast way to populate an object with array-like properties this.length = 0; Array.prototype.push.apply( this, elems ); return this; }, 

这是因为jquery查询的任何结果都是数组。