如何在javascript中的对象的开头添加属性 [英] How to add a property at the beginning of an object in javascript
本文介绍了如何在javascript中的对象的开头添加属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有
var obj = {'b': 2, 'c': 3};
我想在该对象的开头(而不是结尾)添加一个属性:
And i would like to add a property at the beginning (not at the end) of that object:
var obj = {'a': 1, 'b': 2, 'c': 3};
有一种干净的方法吗?
推荐答案
JavaScript对象是无序的.没有开始或结束.如果要订购,请使用数组.
JavaScript objects are unordered. There is no beginning or end. If you want order, use an array.
var arr = [
{ key: 'b', value: 2 },
{ key: 'c', value: 3 }
];
You can then add to the front of it with unshift
:
arr.unshift({ key: 'a', value: 1 });
这篇关于如何在javascript中的对象的开头添加属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文