简体   繁体   English

将类似数组的对象转换成数组的最佳方法?

[英]Best way to turn an array-like object into an array?

Suppose we have the following: 假设我们有以下内容:

var o = {"1": 1, "2": 2, "5": 5};

And I wanted to turn it into what I would get if I did: 我想将其转化为如果我能得到的结果:

var o = []; o[1] = 1, o[2] = 2, o[5] = 5;

How could I do this? 我该怎么办?

Try this: 尝试这个:

var o = { ... }; // your object
var oArr = [];
for (var i in o) {
    if (parseInt(i) == i) {
        oArr[parseInt(i)] = o[i];
    }
}

Notice that it won't accept keys that are non numeric. 请注意,它将不接受非数字键。

If you have a proper length property, it's really easy: 如果您具有适当的length属性,那么这很简单:

var o = {"1": 1, "2": 2, "5": 5, 'length' : 6};
o = Array.prototype.slice.call(o); // [undefined, 1, 2, undefined, undefined, 5]

If you don't have the length property, you can compute it: 如果没有length属性,则可以计算它:

var o = {"1": 1, "2": 2, "5": 5};    

o.length = Object.keys(o).reduce(function(max,key){
  return isNaN(key) ? max : Math.max(max, +key);
},-1) + 1;

o = Array.prototype.slice.call(o); // [undefined, 1, 2, undefined, undefined, 5]

One thing to note, though, when you access a property of an object, it is always converted to a string, so the following will work for your example, even if o is not an array: 不过,需要注意的一件事是,当您访问对象的属性时,该对象始终会转换为字符串,因此即使o不是数组,以下示例也适用于您的示例:

var o = {"1": 1, "2": 2, "5": 5};
o[1] // 1
o[2] // 2
o[5] // 5
o[0] // undefined

You should not be doing that, 1. You are not sure about how big the maximum index value can be. 您不应该这样做,1.您不确定最大索引值可以多大。 2. There could be lots of gaps, those indexes in the array will be null, 2.可能会有很多空白,数组中的索引将为null,

So, just use a string conversion of the index number and look it up in the same object. 因此,只需使用索引号的字符串转换并在同一对象中查找它即可。

 var o = {"1": 1, "2": 2, "5": 5};
 var index = 5;
 o[index.toString()]  // gives 5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM