[英]Array adds 'undefined' at start of the list - throws off counter and list display
我設法整理了一段代碼,提示用戶輸入名稱列表,並一直這樣做直到用戶輸入“ 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 ...
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]
位置。
首先增加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.","");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.