如何在JavaScript数组中添加新的复杂条目? [英] How do I add a new complex entry to a javascript array?

查看:113
本文介绍了如何在JavaScript数组中添加新的复杂条目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  var users = [我的Node.js / Express网页应用程序中的JavaScript数据结构如下: 
{username:'x',密码:'secret',电子邮件:'x@x.com'}
,{username:'y',密码:'secret2',电子邮件:'y @ x.com'}
];

收到新用户的表单值后:

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

我想添加新用户的数据结构应该导致以下结构:

  users = [
{username:'x ',密码:'secret',电子邮件:'x@x.com'}
,{username:'y',密码:'secret2',电子邮件:'y@x.com'}
,{username:'z',password:'secret3',email:'z@x.com'}
];

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

解决方案

您可以使用 push方法将元素添加到数组的末尾。

  var users = [
{username:'x',密码:'secret',电子邮件:'x@x.com'}
,{username:'y',密码:'secret2',电子邮件:'y@x.com' }
];

users.push({username:'z',password:'secret3',email:'z@x.com'})

您也可以设置 users [users.length] = the_new_element 但我不认为好的。


I have a JavaScript data structure like the following in my Node.js/Express web app:

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.

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.

这篇关于如何在JavaScript数组中添加新的复杂条目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆