我尝试摆弄代码,这是我最接近完成所需功能的代码。截至目前,它重写了索引[0],使索引[1]保持不变,并添加了索引[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}
};
}
现在仅关注用户名
答案 0 :(得分:2)
您不需要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)