简体   繁体   English

数组在列表的开头添加'undefined' - 抛出计数器和列表显示

[英]Array adds 'undefined' at start of the list - throws off counter and list display

I managed to put together a code that prompts users for a list of names and keeps doing so until user inputs 'q'. 我设法整理了一段代码,提示用户输入名称列表,并一直这样做直到用户输入“ q”。 Each of the entered names are added to an array and later displayed (additionally, the prompt box displays the total number of items entered). 每个输入的名称将添加到数组中,然后显示(另外,提示框将显示输入的项目总数)。

When i run the code, it displays all entered items PLUS the item 'undefined' on top... and I noticed that when i get the prompt and start typing names, it goes from 0 to 2, then 3, 4, etc. 当我运行代码时,它显示所有输入的项目加上顶部的项目'undefined'...我注意到当我得到提示并开始输入名称时,它会从0变为2,然后变为3,4等。

Where is the 'undefined' coming from, what did I do wrong? “未定义”来自哪里,我做错了什么?

Also, please note that while the code does run, it returns an error 'length' is null or not an object, but list still displays. 另外,请注意,代码在运行时会返回错误“长度”为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 ...
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;

should be 应该

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++;

The nameItems[0] location is never changed otherwise. 否则不会更改nameItems[0]位置。

You first increase i and then you are storing the userInput . 首先增加i ,然后存储userInput So, you are effectively skipping the first array entry. 因此,您实际上是在跳过第一个数组条目。 Do it the other way around and your 'undefined' entry is gone. 反过来做,你的'未定义'条目消失了。

Note: if you throw your lines of code around a bit, it all will become much nicer: 注意:如果你抛出一些代码行,那么一切都会变得更好:

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.","");   
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM