在 JavaScript 中创建类似数组的对象 [英] Creating array-like objects in JavaScript
问题描述
在 JavaScript 中,有些对象伪装成数组(或类数组").这些对象是 arguments
、NodeList
s(从 getElementsByClassName
等返回)和 jQuery 对象.
In JavaScript, there are objects that pretend to be arrays (or are "array-like"). Such objects are arguments
, NodeList
s (returned from getElementsByClassName
, etc.), and jQuery objects.
当 console.log
ged 时,它们显示为数组,但它们不是.我知道为了像数组一样,一个对象必须有一个 length
属性.
When console.log
ged, they appear as arrays, but they are not. I know that in order to be array-like, an object must have a length
property.
所以我做了一个这样的对象":
So I made an "object" like this:
function foo(){
this.length = 1;
this[0] = "bar";
}
var test = new foo;
当我 console log(test)
时,我得到(如预期的)一个 foo
对象.我可以使用
When I console log(test)
, I get (as expected) a foo
object. I can "convert" it to an array using
Array.prototype.slice.call(test)
但是,我不想转换它,我希望它像数组一样.我如何制作一个类似数组的对象,以便在 console.log
ged 时,它显示为一个数组?
But, I don't want to convert it, I want it to be array-like. How do I make an array-like object, so that when it's console.log
ged, it appears as an array?
我尝试设置 foo.prototype = Array.prototype
,但是 console.log(new foo)
仍然显示一个 foo
对象,并且不是数组.
I tried setting foo.prototype = Array.prototype
, but console.log(new foo)
still shows a foo
object, and not an array.
推荐答案
具体取决于控制台.对于 Chrome 开发者控制台和 Firebug 中的自定义对象,您需要 length
和 splice
属性.splice
也必须是一个函数.
Depends specifically on the console. For custom objects in Chrome's developer console, and Firebug you'll need both the length
and splice
properties. splice
will also have to be a function.
a = {
length: 0,
splice: function () {}
}
console.log(a); //[]
但是需要注意的是,没有官方标准.
It's important to note, however, that there is no official standard.
jQuery (v1.11.1) 在内部使用以下代码来确定对象应该使用 for
循环还是 for..in
循环:>
The following code is used by jQuery (v1.11.1) internally to determine if an object should use a for
loop or a for..in
loop:
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
循环进行迭代.
Note that it's possible to have an object that appears in the console as an array ([]
) but that gets iterated over with a for..in
loop in jQuery, or an object that appears as an object in the console ({}
) but that gets iterated over with a for
loop in jQuery.
这篇关于在 JavaScript 中创建类似数组的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!