该脚本的工作原理是要求用户添加或删除数组中的项目。然后要求继续这个循环。这里的问题是我的脚本似乎与用户的输入(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";
}
}
最佳答案
您的循环永远不允许它循环遍历所有项目,因为如果项目不匹配,它就会在第一次迭代时中断。
break
语句应该位于 if
block 中,而不是位于 else
block 中 - 请改用此:
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";
}
另外,请注意,它正在寻找完全匹配、区分大小写、相同的标点符号等等。如果您希望它更宽松一点,您需要修改脚本以将两个字符串转换为小写并在比较之前去掉标点符号。
编辑:刚刚注意到其他事情 - 需要在循环之外完成空列表的测试。我更新了上面的代码以反射(reflect)这一点。
关于javascript - 尝试从数组中添加和删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15772736/