[英]push an assoc object into array
says I've this : 说我有这个:
var user = [{'id':1,'gender':'male'},{'id':2,'gender':'female'}]
I want to use push() to insert 我想用push()插入
'owner':true
into the first array so that it become like this 放入第一个数组中,使其变为这样
var user = [{'id':1,'gender':'male','owner':true},{'id':2,'gender':'female'}]
I tried 我试过了
user[0].push({'owner':true});
but it doesn't work tht way. 但这行不通。
@Kim Gysen gave you a solution that works. @Kim Gysen为您提供了有效的解决方案。 I think you're getting the logic between Arrays and Objects confused I just wanted to give you a solution using only JavaScript that may help you understand just what's going on here.
我认为您对数组和对象之间的逻辑感到困惑,我只是想为您提供一个仅使用JavaScript的解决方案,它可以帮助您了解此处的情况。 Using libraries like jQuery are a great way to save time but for you I think it would be helpful to have a more comprehensive understanding.
使用jQuery之类的库是节省时间的好方法,但是对您来说,我认为更全面的了解会有所帮助。
user[0]['owner'] = true;
In the code above you are accessing your array by the 0th index which in this case is "'id':1" and adding a new property to it using Bracket Notation. 在上面的代码中,您将通过第0个索引(在本例中为“'id':1”)访问数组,并使用括号表示法向其添加新属性。 Another way to do this would be using Dot Notation:
另一种方法是使用点表示法:
user[0].owner = true;
Think about the process of adding a property to an object: 考虑将属性添加到对象的过程:
var myObj = {};
myObj['newKey'] = "I'm a new value";
myObj['newKey2'] = "I'm an even newer value!";
The reason I gave you an answer is it may seem convenient to use jQuery but understanding JavaScript principles and syntax will help you out in the long run. 我给您答案的原因是,使用jQuery似乎很方便,但从长远来看,了解JavaScript的原理和语法将对您有所帮助。 Some good resources for you I'd suggest are CodeSchool and CodeAcademy
我建议您从CodeSchool和CodeAcademy获得一些好的资源
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.