2

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

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

4

2 回答 2

6

您可以使用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,但我认为这看起来不太好。

于 2012-06-22T18:14:55.427 回答
1

您可以通过多种方式将项目添加到数组中:

Push - 添加到最后(想想堆栈)

Unshift - 添加到开头(想想队列)

Splice - 通用(push 和 unshift 是对此的包装)

于 2012-06-22T18:23:10.857 回答