在 JavaScript 中,有些对象伪装成数组(或“类数组”)。这些对象是 arguments
、NodeList
(从 getElementsByClassName
等返回)和 jQuery 对象。
console.log
ged 时,它们显示为数组,但实际上不是。我知道为了像数组一样,对象必须具有 length
属性。
所以我做了一个这样的“对象”:
function foo(){
this.length = 1;
this[0] = "bar";
}
var test = new foo;
当我 console log(test)
时,我(如预期的那样)得到一个 foo
对象。我可以使用
Array.prototype.slice.call(test)
但是,我不想转换它,我希望它类似于数组。我如何制作一个类似数组的对象,以便在 console.log
ged 时,它显示为一个数组?
我尝试设置 foo.prototype = Array.prototype
,但是 console.log(new foo)
仍然显示一个 foo
对象,并且不是数组。
最佳答案
具体取决于控制台。对于 Chrome 开发人员控制台和 Firebug 中的自定义对象,您需要 length
和 splice
属性。 splice
也必须是一个函数。
a = {
length: 0,
splice: function () {}
}
console.log(a); //[]
但是,请务必注意,没有官方标准。
jQuery (v1.11.1) 在内部使用以下代码来确定对象是否应该使用 for
循环或 for..in
循环:
function isArraylike( obj ) {
var length = obj.length,
type = jQuery.type( obj );
if ( type === "function" || jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.nodeType === 1 && length ) {
return true;
}
return type === "array" || length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj;
}
请注意,有可能有一个对象作为数组 ([]
) 出现在控制台中,但它会被 for..in
循环迭代jQuery,或在控制台 ({}
) 中显示为对象但在 jQuery 中使用 for
循环迭代的对象。
关于javascript - 在 JavaScript 中创建类数组对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11886578/