是什么让 Firebug/Chrome 控制台将自定义对象视为数组? [英] What makes Firebug/Chrome console treat a custom object as an array?

查看:23
本文介绍了是什么让 Firebug/Chrome 控制台将自定义对象视为数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用 jQuery 进行开发时,我经常发现自己在 Chrome/Firebug 控制台中输入选择器并查看它们给我的信息.它们的格式总是很好,就好像它们是数组一样:

When I am developing in jQuery, I frequently find myself typing selectors into the Chrome/Firebug console and seeing what they give me. They are always nicely formatted as if they were arrays:

我正在尝试弄清楚是什么使控制台将对象视为数组.例如,以下自定义对象不被视为数组:

I am trying to work out what it is that makes the console treat an object as an array. For instance, the following custom object is not treated as an array:

function ElementWrapper(id) {
    this[0] = document.getElementById(id);
}

如果我随后添加一个 length 属性和一个 splice 方法,它会神奇地作为一个数组工作,任何带有整数键的属性都被视为数组的成员:

If I then add a length property and a splice method, it magically works as an array, with any properties with integer keys treated as members of the arrays:

function ElementWrapper(id) {
    this[0] = document.getElementById(id);
    this.length = 1;
    this.splice = Array.prototype.splice;
}

所以本质上我的问题是:是什么决定了控制台是否将对象显示为数组?是否有任何理由,或者它是完全任意的如果一个对象具有这些属性,它必须是一个数组?"如果有,决定性的属性是什么?

So essentially my question is: what determines whether the console displays an object as an array? Is there any rationale to it, or is it a completely arbitrary "if an object has these properties, it must be an array?" If so, what are the decisive properties?

推荐答案

这就是 Firebug 的 isArray 方法的作用:(来自 Firebug 源码)

This is what Firebug's isArray method does: (from the Firebug source)

if (!obj)
    return false;
else if (isIE && !isFunction(obj) && typeof obj == "object" && isFinite(obj.length) && obj.nodeType != 8)
    return true;
else if (isFinite(obj.length) && isFunction(obj.splice))
    return true;
else if (isFinite(obj.length) && isFunction(obj.callee)) // arguments
    return true;
else if (instanceOf(obj, "HTMLCollection"))
    return true;
else if (instanceOf(obj, "NodeList"))
    return true;
else
    return false;

当然,这些检查都不能确保对象是真正的 JavaScript 数组,但它们可以合理地猜测对象是否是伪数组,这反过来又为您提供了一种方便的类似数组的表示来进行调试.

Of course, none of these checks ensures that the object is a true JavaScript array, but they do a reasonable job of guessing whether an object is a pseudo-array, which in turn gives you a convenient array-like representation for debugging.

Chrome 可能会也可能不会使用这些相同的检查,并且 Firefox 4 中的新 Web 控制台不会将除真正数组之外的任何内容识别为数组.

Chrome may or may not use these same checks, and the new Web Console in Firefox 4 doesn't recognize anything other than true arrays as arrays.

这篇关于是什么让 Firebug/Chrome 控制台将自定义对象视为数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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