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

How do I add a new complex entry to a javascript array?

本文关键字:添加 javascript 数组 复杂      更新时间:2023-09-26

我的 Node.js/Express Web 应用程序中有一个如下所示的 JavaScript 数据结构:

var users = [
    { username: 'x', password: 'secret', email: 'x@x.com' }
  , { username: 'y', password: 'secret2', email: 'y@x.com' }
];

收到新用户发布的表单值后:

{ 
  req.body.username='z', 
  req.body.password='secret3', 
  req.body.email='z@x.com'
}

我想将新用户添加到数据结构中,这应该会导致以下结构:

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' }
];

如何使用已发布的值向我的用户数组添加新记录?

可以使用 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' } )

你也可以设置users[users.length] = the_new_element但我认为这看起来不太好。

您可以通过多种方式向数组添加项:

推送 - 添加到末尾(思考堆栈)

取消移位 - 添加到开头(想想队列)

拼接 - 通用(push 和 unshift 是围绕此的包装器)