简体   繁体   中英

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'. 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.

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.

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.

You first increase i and then you are storing the 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.","");   
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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