我是新來的JavaScript和試圖完成什麼應該是一個簡單的任務,讓用戶與簡單的聯繫人數組進行交互,我努力尋找正確的語法來循環選擇變量,直到用戶輸入0退出,我已經嘗試了while循環和,但只是不知道究竟在何處我應該把循環和建議將不勝感激與開關的Javascript查詢
var Contact = {
//Initialise the contact
init: function(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
},
//Display the contact details
describe: function() {
var description = "Last name : " + this.lastName + ", first name: " + this.firstName;
return description
}
};
var contact1 = Object.create(Contact);
contact1.init("John", "Smith");
var contact2 = Object.create(Contact);
contact2.init("Jane", "Doe");
var contacts = [];
contacts.push(contact1);
contacts.push(contact2);
console.log("Welcome to your contacts manager!");
console.log("1: List contacts");
console.log("2: Add a contact");
console.log("0: Quit");
var choice = "";
choice = prompt("Enter 1, 2 or 0");
//while (choice !== "0") {
switch (choice) {
case "1":
console.log("Here's the list of all your contacts:");
contacts.forEach(function (contact) {
console.log(contact.describe());
});
console.log("1: List contacts");
console.log("2: Add a contact");
console.log("0: Quit");
break;
case "2":
contacts.push(prompt("Enter new name: "));
console.log("Contact added");
console.log("1: List contacts");
console.log("2: Add a contact");
console.log("0: Quit");
break;
case "0":
console.log("Goodbye");
console.log("1: List contacts");
console.log("2: Add a contact");
console.log("0: Quit");
break;
default:
console.log("Invalid Entry");
console.log("1: List contacts");
console.log("2: Add a contact");
console.log("0: Quit");
break;
}
我可以問你一個關於這個while循環的問題,它通過第一次工作正常,但如果我使用push添加聯繫人,然後嘗試列出數組失敗,因爲它說contact.describe不再是一個功能? –
是的,所以它是在你的代碼中,你嘗試初始化2個值,並在輸入你的名字作爲單一值,沒有問題我已經更新你的代碼,請現在嘗試請參閱更新的部分。 –
謝謝你,現在有道理 –