1

Ladies and gentlemen,

I'm stuck. I've been pondering this (and obviously have failed since I'm asking for your valuable assistance) in trying to get my code to work.

I need to come up with a simple (...I'm sorry, i'm new to this) code that prompt users to keep entering names using a loop. If the user does not enter 'q'(without quotes) and if the value entered is NOT null, then the value entered should be added to the array (in my case, names).

If the user enters 'q', the loop should stop, 'q' will not be entered in the array and the list of names should be printed (through the second function in my code).

Here's what I have so far... I can make the code work if I tell the loop to run i<5... it runs 5 times and then it stops. But it fails if i do i < names.length..it causes it say that length is null or not an object (on line 10). That's problem one. And for the life of me, I can't figure out how to add the logic that will run the loop until user enters q.

Please help!

Thank you.

function getNames(){
var names = new Array();
    for(i=0;i<names.length;i++){ /*if i do i=0;i<5;i++, the code works; it doesn't with this*/
    names[i] = prompt("Enter an item to add to the Name list (enter \'q\' to quit","");
}
printNames(names);
}

function printNames(names) {
for(x=0; x < names.length;x++){
document.write(names[x] + '<br />');
}

}
getNames();
printNames();
4

2 回答 2

2

我确信在你的课堂/书中某处谈到了while loops。因此,如果您希望他们无限制地继续输入,您想使用 while 循环。

while (myCondition===true) {
  //do something
}

现在看看你的 for 循环,找出它失败的原因。

for(i=0;i<names.length;i++)

看看它在做什么:

  • 我 = 0
  • 名称.长度 = 0

0 < 0吗?

于 2012-12-24T16:08:13.933 回答
0

从问题 1 开始:

您的名称数组以长度属性 0 开头,因此您的第一个 for 循环不会运行,因为 0 不小于 0。

这导致了问题2:

再次,因为您的名称数组中没有输入任何内容,您的第二个 for 循环再次什么也不做,也不执行 document.write,因为您的数组的长度属性仍然为 0。

于 2012-12-24T16:15:14.013 回答