[英]Making an object become an array
Is it possible to make a JavaScript object become an array? 是否可以使JavaScript对象成为数组? That is, while keeping its existing attributes, start behaving like an array with regard to
length
, push
, forEach
etc? 也就是说,在保留其现有属性的同时,在
length
, push
, forEach
等方面开始表现得像一个数组吗? I had the vague idea that this might be possible by reassigning the prototype but some attempts to do this by trial and error haven't yielded any results. 我有一个模糊的想法,那就是可以通过重新分配原型来实现这一点,但是通过反复试验来实现这一点的尝试并未产生任何结果。
No, you cannot. 你不能。 While you could theoretically (through non-standard ways ) reassign the prototype, it will not change its internal
[[Class]]
and get a magic .length
property. 从理论上讲,您可以(通过非标准方式 )重新分配原型,但它不会更改其内部
[[Class]]
并具有不可思议的.length
属性。
Instead, try to copy all the properties of the object onto a new array. 而是尝试将对象的所有属性复制到新数组上。
I'm not sure why you'd want to do this, other than for access to .length
, .push()
, and forEach
, as you mentioned. 除了您提到的访问
.length
, .push()
和forEach
,我不确定您为什么要这样做。 As far as I know, you cannot force these properties/functions to work on an object, but you can certainly get around them: 据我所知,您不能强制这些属性/函数在对象上运行,但是您可以绕开它们:
.length
(from here ): .length
(从此处开始 ):
Object.size = function(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
// Get the size of an object
var size = Object.size(myObj);
.push()
: .push()
:
obj.key = value; //there isn't a much shorter way to add something to an object since you have to specify a key and a value
forEach
: forEach
:
for(key in obj){
var value;
if(obj.hasOwnProperty(key)){
value = obj[key]; //you now have access to the key and the value in each iteration of obj
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.