[英]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
但我認為效果並不理想。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.