在创建JavaScript数组状物体 [英] Creating array-like objects in JavaScript
问题描述
在JavaScript中,有对象pretend是阵列(或属于阵列状)。这样的对象是参数
,节点列表
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,他们似乎阵列,但他们不是。我知道,为了要阵列状,一个对象必须有一个长度
属性。
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;
当我控制台日志(测试)
,我得到(预期)一个富
对象。我可以使用转换它一个数组
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(新富)
仍显示一个富
的对象,而不是一个数组。
I tried setting foo.prototype = Array.prototype
, but console.log(new foo)
still shows a foo
object, and not an array.
推荐答案
取决于具体的控制台上。对于Chrome的开发者控制台自定义对象和Firebug的,你需要两个长度
和拼接
属性。 拼接
也必须是一个函数。
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.
以下code用于的jQuery(v1.11.1)在内部确定对象是否应该使用为
环或的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;
}
请注意,它是可能有,在控制台显示为一个数组( []
),但被遍历了的对象..in
循环jQuery中,或者出现在控制台中的对象的对象( {}
),但被遍历以在jQuery的
循环。
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屋!