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 ...
should be
The
nameItems[0]location is never changed otherwise.