2

私はなんとかユーザーに名前のリストを要求し、ユーザーが「q」を入力するまでそうし続けるコードをまとめることができました。入力された各名前は配列に追加され、後で表示されます(さらに、プロンプトボックスには、入力されたアイテムの総数が表示されます)。

コードを実行すると、入力されたすべてのアイテムに加えて、アイテム「undefined」が一番上に表示されます...プロンプトが表示されて名前の入力を開始すると、0から2、次に3、4などになります。

「未定義」はどこから来ているのですか、私は何を間違えましたか?

また、コードの実行中は、「長さ」がnullであるかオブジェクトではないというエラーが返されますが、リストは引き続き表示されることに注意してください。

function getNames(){
var nameItems = new Array();
var i; 
i = 0;
var userInput; 
userInput = '';
var totalItems;
totalItems = nameItems.length;
do 
{
    if ( userInput > '') { /*performs task only if something is received from     userInput, doesn't add value to array if nothing is entered.*/
    i++;
    nameItems[i] = userInput;
    }
userInput = prompt("Enter a name to add to your favorite names list (enter \'q\'     to quit. - " + nameItems.length + " items entered.","");   
} while ...
4

2 に答える 2

4
if ( userInput > '') { /*performs task only if something is received from     userInput, doesn't add value to array if nothing is entered.*/
i++;
nameItems[i] = userInput;

する必要があります

if ( userInput > '') { /*performs task only if something is received from     userInput, doesn't add value to array if nothing is entered.*/
nameItems[i] = userInput;
i++;

それ以外の場合、nameItems[0]場所は決して変更されません。

于 2012-12-27T20:08:44.050 に答える
3

最初に増加iしてから、userInput. したがって、最初の配列エントリを効果的にスキップしています。逆にすると、「未定義」のエントリはなくなります。

注: コード行を少し変更すると、すべてがより良くなります。

while((userInput = getInput()) != 'q')
{
    nameItems[i] = userInput;
    i++;
}

function getInput()
{
  return prompt("Enter a name to add to your favorite names list (enter \'q\'     to quit. - " + nameItems.length + " items entered.","");   
}
于 2012-12-27T20:08:42.540 に答える