【问题标题】:Add a new object in an array through prompt通过提示在数组中添加新对象
【发布时间】:2018-12-02 23:32:55
【问题描述】:

我试过摆弄代码,这是我完成我想要的最接近的事情。截至目前,它重写了 index[0],保留 index[1] 不变,并添加了 index [2]。我正在尝试让它保持 index[0] 和 index[1] 不变,只需添加新索引。

// Store all accounts and information
var account = [
{
    username: "John Sant",
    password: "dog123",
    balance: 450
},
{
    username: "Rebecca Dunson",
    password: "Munco38",
    balance: 1276
}
]

// Create new user or proceed to sign in
var task = prompt("Do you have an account? (Yes or No)")
if(task.toLowerCase() === "no"){
    for(i = 0; i <= account.length; i++){
        var newUsername = prompt("Enter your first and last name:")
        account[i++] = {username: newUsername}
};
} 

现在只关注用户名

【问题讨论】:

标签: javascript arrays object indexing


【解决方案1】:

您不需要for 循环。您可以在 accounts 数组中添加一个新值 push() 来创建一个新条目。

// Store all accounts and information
var account = [{
    username: "John Sant",
    password: "dog123",
    balance: 450
  },
  {
    username: "Rebecca Dunson",
    password: "Munco38",
    balance: 1276
  }
]

// Create new user or proceed to sign in
var task = prompt("Do you have an account? (Yes or No)")
if (task.toLowerCase() === "no") {
  var newUsername = prompt("Enter your first and last name:")
  var newAccount = {username: newUsername}
  newAccount.password = prompt("Enter a new password:")
  account.push(newAccount)
};

// log all accounts
console.log(account)

【讨论】:

  • 如果这只是一个解释,我会投票给你:)
  • @KickButtowski,我不确定我是否理解。
  • @Mark_M 现在我如何才能定位最新的索引来添加密码?
  • @sloan 我的意思是如果没有代码,我会投票给你:)。斯隆评论很好地证明了我为什么这么说。提供代码不会帮助任何人。
  • @Sloan 我会将对象保存到变量中,提示用户输入密码,将其添加为属性,然后将对象推送到列表中。请参阅编辑后的答案。
猜你喜欢
  • 2021-06-21
  • 1970-01-01
  • 2022-10-16
  • 1970-01-01
  • 1970-01-01
  • 2020-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多