2013-04-02 20 views
1

該腳本通過要求用戶添加或刪除陣列中的項目來工作。然後要求繼續這個循環。這裏的問題是我的腳本似乎不匹配我的用戶輸入(removeItem)到列表中的項目(myList [i])。我迷失在爲什麼這是無法匹配。嘗試添加和刪除陣列中的項目

// new method for removing specific items from a list 
Array.prototype.remove = function(from,to) { 
    var rest = this.slice((to || from) + 1 || this.length); 
    this.length = from < 0 ? this.length + from : from; 
    return this.push.apply(this, rest); 
}; 

printList = function() { 
    var listLength = myList.length; 
    for (i = 0; i < listLength; i++) { 
     document.write(i + ":"); 
     document.write(myList[i] + "<br/>"); 
    }; 
    document.write("<br/><br/>"); 
}; 

// initial list 
var myList = new Array(); 
if (myList.length === 0) { 
    document.write("I have " + myList.length + " item in my list. It is: <br/>"); 
} 
else { 
    document.write("I have " + myList.length + " items in my list. They are: <br/>"); 
} 
printList(); 

var continueAdding = "yes"; 
var askToContinue = ""; 

while (continueAdding === "yes") { 
    // loop 
    var askUser = prompt("What do you want to [A]dd or [R]emove an item to your inventory?").toUpperCase(); 
    switch (askUser) { 
     case "A": { // add an user specified item to the list 
      var addItem = prompt("Add something to the list"); 
      myList.push(addItem); 
      printList(); 
      break; 
     } 
     case "R": { // remove an user specified item from the list 
      var removeItem = prompt("what do you want to remove?"); 
      var listLength = myList.length; 
      for (i = 0; i < listLength; i++) { 
       if (removeItem === myList[i]) { 
        document.write("I found your " + removeItem + " and removed it.<br/>"); 
        myList.remove(i); 
       } 
       else { 
        document.write(removeItem + " does not exist in this list.<br/>"); 
        break; 
       } 
       if (myList.length === 0) { 
        myList[0] = "Nada"; 
       } 
      }; 
      printList(); 
      break; 
     } 
     default: { 
      document.write("That is not a proper choice."); 
     } 
    }; 

    askToContinue = prompt("Do you wish to continue? [Y]es or [N]o?").toUpperCase(); // ask to continue 
    if (askToContinue === "Y") { 
     continueAdding = "yes"; 
    } 
    else { 
     continueAdding = "no"; 
    } 
} 

回答

1

您的循環永遠不會允許它循環遍歷所有項目,因爲如果項目不匹配,它會在第一次迭代時斷開。

break的說法應該是在if塊,而不是在else塊 - 用這個來代替:

for (i = 0; i < listLength; i++) { 
    if (removeItem === myList[i]) { 
     document.write("I found your " + removeItem + " and removed it.<br/>"); 
     myList.remove(i); 
     break; 
    } 
    else { 
     document.write(removeItem + " does not exist in this list.<br/>"); 
    } 
}; 

if (myList.length === 0) { 
    myList[0] = "Nada"; 
} 

另外,還要注意它尋找一個精確匹配,大小寫敏感的,同樣的標點符號,和所有。如果您希望它稍微寬鬆一點,您需要修改腳本以將兩個字符串轉換爲小寫字母,並在比較它們之前去掉標點符號。

編輯:只是注意到別的東西 - 測試一個空列表需要在循環之外完成。我更新了上面的代碼以反映這一點。