JavaScript嵌套循环不起作用

时间:2016-06-11 04:08:00

标签: javascript

我正在使用嵌套循环进行分配,询问用户输入的4个猜测信息并通过警告打印出来。问题是prompt只重复一次。

var myArray = new Array(2);
for(var i=0; i<2; i++){
    for(var j=0; j<2; j++){
        myArray[i][j] = prompt("Enter Guess First Name.");
        myArray[i][j] = prompt("Enter Guess Last Name.");
        myArray[i][j] = prompt("Enter Guess Phone.");
        myArray[i][j] = prompt("Enter Guess Address.");
    }
}
alert("first person : " + myArray[0][0]);
alert("second person : " + myArray[0][1]);
alert("third person : " + myArray[1][0]);
alert("fourth person : " + myArray[1][1]);

2 个答案:

答案 0 :(得分:3)

尝试将其更改为:

var myArray = new Array();
for(var i=0; i<2; i++){
    myArray[i]=[]; // <- this is what you're missing
    for(var j=0; j<2; j++){
        myArray[i][j] = prompt("Enter Guess First Name.");
        myArray[i][j] = prompt("Enter Guess Last Name.");
        myArray[i][j] = prompt("Enter Guess Phone.");
        myArray[i][j] = prompt("Enter Guess Address.");
    }
}
alert("first person : " + myArray[0][0]);
alert("second person : " + myArray[0][1]);
alert("third person : " + myArray[1][0]);
alert("fourth person : " + myArray[1][1]);

答案 1 :(得分:0)

代码在第一个提示符后崩溃,因为myArray[i]未初始化。

说,我会继续给出更好的答案:

这里的问题是循环没有意义。

在一天结束时,myArray[i][j]的值将是&#34; Guess Address&#34;的输入。

myArray[i][j] = prompt("Enter Guess First Name.");
myArray[i][j] = prompt("Enter Guess Last Name."); // overwrites previous assignment
myArray[i][j] = prompt("Enter Guess Phone."); // overwrites previous assignment
myArray[i][j] = prompt("Enter Guess Address."); // overwrites previous assignment

为了以你想要的方式填充数组,你将只是在没有循环的情况下问四个问题:

myArray[0][0] = prompt("Enter Guess First Name.");
myArray[0][1] = prompt("Enter Guess Last Name.");
myArray[1][0] = prompt("Enter Guess Phone.");
myArray[1][1] = prompt("Enter Guess Address.");

注意:可能不是你的情况,但在一般情况下,最好有一个对象来存储这类数据:

var guest = {};
guest.firstName = prompt("Enter Guess First Name.");
guest.lastName = prompt("Enter Guess Last Name.");
guest.phone = prompt("Enter Guess Phone.");
guest.address = prompt("Enter Guess Address.");

更新:鉴于您坚持使用嵌套循环计划,我将为您提供此选项:

// nested array with the questions
var questions = [
    [ "Enter Guess First Name.", "Enter Guess Last Name." ],
    [ "Enter Guess Phone.", "Enter Guess Guess Address." ],
];

// initialize first-level array for the answers
var myArray = new Array(2);
for(var i=0; i<2; i++){
    myArray[i] = new Array(2); // initialize nested array at i
    for(var j=0; j<2; j++){
        myArray[i][j] = prompt(questions[i][j]); // ask the question at the position (i,j)
    }
}

我们在这里做的是创建一个问题矩阵(即:一个数组的数组),这将允许我们执行嵌套循环。

  • 在循环的第一步中,我们有i=0j=0,然后是questions[0][0] == "Enter Guess First Name."
  • 在循环的第二步中,我们有i=0j=1,然后是questions[0][1] == "Enter Guess Last Name."
  • 在循环的第3步中,我们有i=1j=0,然后是questions[1][0] == "Enter Guess Phone."
  • 在循环的第4步中,我们有i=1j=1,然后是questions[1][1] == "Enter Guess Guess Address."

嵌套循环myArray的结尾将填充每个步骤中提出的问题的答案。