javascript - 通过提示在数组中添加新对象
问题描述
我试过摆弄代码,这是我完成我想要的最接近的事情。截至目前,它重写了 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}
};
}
目前只关注用户名
解决方案
你不需要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)
推荐阅读
- r - 如何将stdin输入转换为R中的列表
- function - 如何在一个函数中找到具有多个输入的最大函数输出?
- typescript - `Parameters` 实用程序类型为只读数组 arg 返回 `never`
- unit-testing - 数据驱动单元测试中的执行控制。(MSUnitTest)
- javascript - 初始化后如何更新 jQuery 无选择器插件上的选项?
- reactjs - 有没有办法在组件安装后以特定间隔更新 react-bootstrap-daterangepicker 的日期范围?
- elixir - 在 Elixir 中切换真假
- android - 获取firebase服务器时间戳的简单日期?如何只获取日期而不是时间
- python - 我的雅虎金融报价数据的 Python BeautifulSoup 刮板坏了。上周有什么变化吗?
- windows - 在 Windows 上从英特尔 SGX enclave 代码访问 uRSP 和 uRBP