[英]How do I add a new complex entry to a javascript array?
I have a JavaScript data structure like the following in my Node.js/Express web app: 我的Node.js / Express网络应用程序中具有如下所示的JavaScript数据结构:
var users = [
{ username: 'x', password: 'secret', email: 'x@x.com' }
, { username: 'y', password: 'secret2', email: 'y@x.com' }
];
After receiving posted form values for a new user: 在收到新用户的已发布表单值之后:
{
req.body.username='z',
req.body.password='secret3',
req.body.email='z@x.com'
}
I'd like to add the new user to the data structure which should result in the following structure: 我想将新用户添加到数据结构中,这将导致以下结构:
users = [
{ username: 'x', password: 'secret', email: 'x@x.com' }
, { username: 'y', password: 'secret2', email: 'y@x.com' }
, { username: 'z', password: 'secret3', email: 'z@x.com' }
];
How do I add a new record to my users array using the posted values? 如何使用发布的值向用户数组添加新记录?
You can use the push method to add elements to the end of an array. 您可以使用push方法将元素添加到数组的末尾。
var users = [
{ username: 'x', password: 'secret', email: 'x@x.com' }
, { username: 'y', password: 'secret2', email: 'y@x.com' }
];
users.push( { username: 'z', password: 'secret3', email: 'z@x.com' } )
You could also just set users[users.length] = the_new_element
but I don't think that looks as good. 您也可以只设置
users[users.length] = the_new_element
但我认为效果并不理想。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.