Javascript对象文字-可以添加重复的键吗? [英] Javascript object literal - possible to add duplicate keys?
本文介绍了Javascript对象文字-可以添加重复的键吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在javascript中,是否可以在对象文字中添加重复的键?如果是这样,那么在首次创建对象之后如何实现呢?
In javascript, is is possible to add duplicate keys in object literal? If it is, then how could one achieve it after the object has been first created.
例如:
exampleObject['key1'] = something;
exampleObject['key1'] = something else;
如何在不覆盖第一个key1的情况下添加第二个key1?
How can I add the second key1 without overwriting the first key1?
推荐答案
否,这是不可能的.它与:
No it is not possible. It is the same as:
exampleObject.key1 = something;
exampleObject.key1 = something else; // over writes the old value
我认为最好的方法是使用数组:
I think the best thing here would be to use an array:
var obj = {
key1: []
};
obj.key1.push("something"); // useing the key directly
obj['key1'].push("something else"); // using the key reference
console.log(obj);
// ======= OR ===========
var objArr = [];
objArr.push({
key1: 'something'
});
objArr.push({
key1: 'something else'
});
console.log(objArr);
这篇关于Javascript对象文字-可以添加重复的键吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文