gpt4 book ai didi

javascript - $ ('h1' ) 如何作为 jQuery 中的数组登录到 Web 控制台?

转载 作者:可可西里 更新时间:2023-11-01 01:51:27 25 4
gpt4 key购买 nike

如果您在浏览器中执行 console.log($('some selector')),它会返回一个数组(第一行):

picture from latest version of chrome web console on Github project page

但请注意,它不是一个instanceof Array,而实际上是the jQuery object。 .

当您执行 console.dir($('h1')) 时,它显示它实际上是 jQuery 对象。

问题是,他们是如何让它在 Web 控制台中看起来像一个数组的?我在 jQuery 源代码中注意到 here他们添加了对一些 Array 和 Object 方法的引用,以及 here他们将 toArray(以及 slice 和其他)添加到 jQuery 对象。 Web 控制台是否以某种方式检查这些方法,如果它找到一个(toArrayindexOfslice 等),它会将其打印为数组?我想从任何自定义对象中获取此行为,例如 Ember.ArrayProxy。当前,当您登录 Ember.ArrayProxy 时,它会显示 > Object 或其他内容,但最好将其显示为数组。

有什么想法吗?

最佳答案

你让你的对象继承 Array 使用原型(prototype),像这样:

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 就是这样做的。作为奖励,由于继承,您可以获得 Array 中的所有方法,以及它附带的索引!

关于javascript - $ ('h1' ) 如何作为 jQuery 中的数组登录到 Web 控制台?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10763086/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com