如何为$(“H1”)登录到Web控制台jQuery中的数组? [英] How is $('h1') logging to the web console as an array in jQuery?

查看:115
本文介绍了如何为$(“H1”)登录到Web控制台jQuery中的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您的console.log($('一些选择'))在浏览器中,它返回看起来像一个数组(第一行):

If you do console.log($('some selector')) in the browser, it returns what looks like an array (first line):

但是请注意,这不是一个的instanceof阵列,但它实际上是<一个href=\"https://github.com/jquery/jquery/blob/ae20e732f02c7e3bdd76324979b1a816c567ec22/src/core.js#L6\">the 的jQuery 对象。

But notice that it's not an instanceof Array, but it's actually the jQuery object.

当你做 console.dir($('H1')),就说明它实际上是jQuery对象。

When you do console.dir($('h1')), it shows it's actually the jQuery object.

问题是,他们是如何使它看起来像它在Web控制台的数组?我在jQuery的源注意到<一href=\"https://github.com/jquery/jquery/blob/ae20e732f02c7e3bdd76324979b1a816c567ec22/src/core.js#L74\">here他们补充参照几个数组和对象的方法,而<一href=\"https://github.com/jquery/jquery/blob/ae20e732f02c7e3bdd76324979b1a816c567ec22/src/core.js#L199\">here他们补充的toArray (和切片等)到的jQuery 对象。在Web控制台以某种方式检查这些方法,如果找到一个(的toArray 的indexOf 等),它打印它作为一个数组?我想获得这种行为的任何自定义对象的,如 Ember.ArrayProxy 。目前,当你登录的 Ember.ArrayProxy 它显示了&GT;对象或什么,但它会是不错的显示它作为一个数组。

The question is, how are they making it look like it's an array in the web console? I noticed in the jQuery source here they add reference to a few Array and Object methods, and here they add toArray (and slice and others) to the jQuery object. Is the web console somehow checking for these methods and if it finds one (toArray, indexOf, slice, etc.), it prints it as an Array? I would like to get this behavior out of any custom object, such as the Ember.ArrayProxy. Currently when you log the Ember.ArrayProxy it shows > Object or whatever, but it would be nice to show it as an array.

任何想法?

推荐答案

您使用阵列原型,像这样让你的对象继承:

You make your object inherit Array using the prototype, like so:

function SomeType() {
    this.push(16);
}

SomeType.prototype = [];
SomeType.prototype.constructor = SomeType; // Make sure there are no unexpected results

console.log(new SomeType()); // Displays in console as [16]

和,当然,所有的jQuery对象是的jQuery 函数/构造的实例,所以这是jQuery的是怎么做的。作为奖励,因继承,你得到所有从阵列的方法,而且也与它来索引!

And, of course, all jQuery objects are instances of the jQuery function/constructor, so that's how jQuery does it. As a bonus, because of the inheritance, you get all the methods from Array, and the indexing that comes with it too!

这篇关于如何为$(“H1”)登录到Web控制台jQuery中的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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