Possible Duplicate:
Does JavaScript Guarantee Object Property Order?可能重复:JavaScript是否保证对象属性顺序?
I would like to know how I can insert a JSON object property at a specific position? Let's assume this Javascript object:
我想知道如何在特定位置插入JSON对象属性?让我们假设这个Javascript对象:
var data = {
0: 'lorem',
1: 'dolor sit',
2: 'consectetuer'
}
I have an ID and a string, like:
我有一个ID和一个字符串,如:
var id = 6;
var str = 'adipiscing';
Now, I would like to insert the id
between 0
and 1
(for example) and it should be like:
现在,我想插入0和1之间的id(例如),它应该像:
data = {
0: 'lorem',
6: 'adipiscing',
1: 'dolor sit',
2: 'consectetuer'
}
How can I do this? Is there any jQuery solution for this?
我怎样才能做到这一点?有没有任何jQuery解决方案?
1 个解决方案
#1
4
To specify an order in which elements of an object are placed, you'll need to use an array of objects, like this:
要指定放置对象元素的顺序,您需要使用对象数组,如下所示:
data = [
{0: 'lorem'},
{1: 'dolor sit'},
{2: 'consectetuer'}
]
You can then push a element to a certain position in the array:
然后,您可以将元素推送到数组中的某个位置:
// Push {6: 'adipiscing'} to position 1
data.splice(1, 0, {6: 'adipiscing'})
// Result:
data = [
{0: 'lorem'},
{6: 'adipiscing'},
{1: 'dolor sit'},
{2: 'consectetuer'}
]
// Access it:
data[0][0] //"lorem"
However, this will render the indices you've specified ({0:
) pretty much useless.
但是,这将呈现您指定的索引({0 :)几乎没用。
#1
4
To specify an order in which elements of an object are placed, you'll need to use an array of objects, like this:
要指定放置对象元素的顺序,您需要使用对象数组,如下所示:
data = [
{0: 'lorem'},
{1: 'dolor sit'},
{2: 'consectetuer'}
]
You can then push a element to a certain position in the array:
然后,您可以将元素推送到数组中的某个位置:
// Push {6: 'adipiscing'} to position 1
data.splice(1, 0, {6: 'adipiscing'})
// Result:
data = [
{0: 'lorem'},
{6: 'adipiscing'},
{1: 'dolor sit'},
{2: 'consectetuer'}
]
// Access it:
data[0][0] //"lorem"
However, this will render the indices you've specified ({0:
) pretty much useless.
但是,这将呈现您指定的索引({0 :)几乎没用。