簡體   English   中英

如何將新的復雜條目添加到javascript數組?

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

我的Node.js / Express網絡應用程序中具有如下所示的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但我認為效果並不理想。

您可以通過多種方式將項目添加到數組中:

推送 -添加到末尾(認為棧)

取消移位 -添加到開頭(認為隊列)

拼接 -通用(推送和unshift是對此的包裝)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM