javascript 删除键后重新索引javascript数组/对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8310270/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reindex javascript array / object after removing a key
提问by joedborg
For example:
例如:
var Cars = {
1: { "Make": "Honda",
"Model": "Accord",
"Color": "Red"
},
2: { "Make": "Honda",
"Model": "Civic",
"Color": "Silver"
},
3: { "Make": "Honda",
"Model": "Jazz",
"Color": "Yellow"
}
If I do a delete.Cars[2];
I will be left with Cars[1] and Cars[3].
如果我做了一个,delete.Cars[2];
我将剩下 Cars[1] 和 Cars[3]。
I need a way (JS or jQuery) so that when I delete a key, the object reindexes. So, in the example above, I'm left with Cars[1] and Cars[2] (which was Cars[3]).
我需要一种方法(JS 或 jQuery),以便当我删除一个键时,对象会重新索引。因此,在上面的示例中,我只剩下 Cars[1] 和 Cars[2](即 Cars[3])。
采纳答案by Elzo Valugi
That is because you dont need the keys for the array.
那是因为您不需要数组的键。
var Cars = [
{
"Make": "Honda",
"Model": "Accord",
"Color": "Red"
},{
"Make": "Honda",
"Model": "Civic",
"Color": "Silver"
},{
"Make": "Honda",
"Model": "Jazz",
"Color": "Yellow"
}
];
alert(Cars[1]['Make']); // Honda
回答by Marc Uberstein
You can have a look at this:
你可以看看这个:
Array: Javascript - Reindexing an array
Object: Algorithm to re-index an array of objects after insertion or drag 'n' drop order change
对象: 在插入或拖动“n”放置顺序更改后重新索引对象数组的算法
It should do the trick :)
它应该可以解决问题:)
Referencing other developers in this thread, and myself, it will be better to use an Array.
参考该线程中的其他开发人员和我自己,最好使用Array。