2
所以我已經在這裏一段時間了,但不知道如何繼續。我的代碼詢問用戶名字,姓氏和年齡3人,然後將其顯示在表格中。用函數內的提示輸入填充數組
<script>
function person(firstName, lastName, age) {
for (var x = 1; x <= 3; x++) {
this.firstName = prompt("Please enter a first name", "");
while (this.firstName == null || this.firstName == "") {
this.firstName = prompt("Invalid input. Please enter a first name", "");
}
this.lastName = prompt("Please enter a last name", "");
while (this.lastName == null || this.lastName == "") {
this.lastName = prompt("Invalid input. Please enter a last name", "");
}
this.age = prompt("Please enter an age", "");
this.age = parseInt(this.age);
while (this.age == null || isNaN(this.age) || this.age < 0) {
this.age = prompt("Not a valid input. Please enter an age", "");
this.age = parseInt(this.age);
}
}
}
var personDetail = new person();
document.writeln("<table>");
\t document.writeln(" <tr>");
\t document.writeln(" <th>First Name</th>");
\t document.writeln(" <th>Last Name</th>");
\t document.writeln(" <th>Age</th>");
\t document.writeln(" </tr>");
\t
\t for (var z = 0; z < 5; z++) {
\t \t document.writeln(" <tr>");
\t \t document.writeln(" <td>" + personDetail.firstName + "</td>");
\t \t document.writeln(" <td>" + personDetail.lastName + "</td>");
\t \t document.writeln(" <td>" + personDetail.age + "</td>");
\t \t document.writeln(" </tr>");
\t } \t
\t
\t document.writeln("</table>");
</script>
我知道我有收集用戶輸入到一個數組,但我不知道怎麼辦。
我試過以下。只是把名字爲例:
<script>
function person(firstName[]) {
for (var x = 1; x <= 3; x++) {
this.firstName[x - 1] = prompt("Please enter a first name", "");
while (this.firstName[x - 1] == null || this.firstName[x - 1] == "") {
this.firstName[x - 1] = prompt("Invalid input. Please enter a first name", "");
}
}
}
var personDetail = new person();
for (var z = 0; z < 3; z++) {
document.writeln(personDetail.firstName[z]);
}
</script>
我知道有更容易的方法可以做到這一點,但我需要使用一個對象具有構造函數。
改變人(名字[])到人創建一個對象(名字) –
我試過了。然而,輸出僅返回用戶的最終輸入。我試圖用firstName創建一個數組,以便每個輸入都作爲一個元素輸入到該數組中,然後我可以在末尾顯示它 – Abd
如果我理解你是正確的,請嘗試下面的代碼https://jsfiddle.net/0v7k1g7n/ – Kirill