[英]how do add to a key value to javascript object
I am trying to learn JS. 我正在努力学习JS。 It seems simple but I am not sure how to do this.
这似乎很简单,但我不知道该怎么做。
having this javascript object based on this good thread 有这个javascript对象基于这个好的线程
var people = { 1: { name: 'Joe' }, 2: { name: 'Sam' }, 3: { name: 'Eve' } };
How do I add the following value 如何添加以下值
4: { name: 'John' }
To get name Eve I write 为了得到夏娃的名字我写
people["1"].name
Assign the anonymous object to it the way you would any other value. 像对待任何其他值一样为其分配匿名对象。
people["4"] = { name: 'John' };
For what it's worth, since your keys are numeric you could also use zero-based indices and make people an array. 对于它的价值,因为你的键是数字的,你也可以使用从零开始的索引并使人成为一个数组。
var people = [ { name: 'Joe' },
{ name: 'Sam' },
{ name: 'Eve' } ];
and 和
alert( people[2].name ); // outputs Eve
people[3] = { name: 'John' };
I think people should be an array : 我认为人们应该是一个阵列:
var people = [
{ name: 'Joe' },
{ name: 'Sam' },
{ name: 'Eve' }
];
as the keys are integers, so you can add a person by : 因为键是整数,所以你可以通过以下方式添加一个人:
people.push({name:'John'});
You can acces to the people by doing : 您可以通过以下方式访问人员:
var somebody = people[1]; /// >>> Sam
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.