我有一个JSON:
var myVar = {
"9":"Automotive & Industrial",
"1":"Books",
"7":"Clothing"
};
我想在开始时添加一个新元素,我希望最终得到这样的结果:
var myVar ={“5”:“电子”,“9”:“汽车和工业”,“1”:“书籍”,“7”:“服装”};
我试过了,但没有用:
myVar.unshift({"5":"Electronics"});
谢谢!
发布于 2012-05-21 19:37:27
就这样做吧:
var myVar = {
"9":"Automotive & Industrial",
"1":"Books",
"7":"Clothing"
};
// if you want to add a property, then...
myVar["5"]="Electronics"; // note that it won't be "first" or "last", it's just "5"
发布于 2012-05-21 19:46:40
根据定义,Javascript对象没有与它们关联的顺序,因此这是不可能的。
如果需要订单,则应该使用对象的数组:
var myArray = [
{number: '9', value:'Automotive & Industrial'},
{number: '1', value:'Books'},
{number: '7', value:'Clothing'}
]
然后,如果要在第一个位置插入某些内容,可以使用数组的unshift方法。
myArray.unshift({number:'5', value:'Electronics'})
//myArray is now the following
[{number:'5', value:'Electronics'},
{number: '9', value:'Automotive & Industrial'},
{number: '1', value:'Books'},
{number: '7', value:'Clothing'}]
这里有更多的细节:JavaScript保证对象属性顺序吗?
发布于 2012-05-21 19:33:44
无法向JSON添加新条目并控制它们的位置。
如果您想处理order奇怪,因为对象是无序的,那么基本上必须创建一个新对象并追加数据。
https://stackoverflow.com/questions/10691409
复制相似问题