首页 > 解决方案 > 通过提示在数组中添加新对象

问题描述

我试过摆弄代码,这是我完成我想要的最接近的事情。截至目前,它重写了 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}
};
} 

目前只关注用户名

标签: javascriptarraysobjectindexing

解决方案


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

// 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)


推荐阅读