简体   繁体   English

如何将新的复杂条目添加到javascript数组?

[英]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但我认为效果并不理想。

You can add items to an array in many ways: 您可以通过多种方式将项目添加到数组中:

Push - adds to the end (think stack) 推送 -添加到末尾(认为栈)

Unshift - adds to the beginning (think queue) 取消移位 -添加到开头(认为队列)

Splice - generic (push and unshift are wrappers around this) 拼接 -通用(推送和unshift是对此的包装)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM