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";
    }
}
4

1 回答 1

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";
}

另外,请注意,它正在寻找完全匹配、区分大小写、相同的标点符号以及所有内容。如果您希望它更宽松一点,您需要修改脚本以将两个字符串转换为小写并在比较它们之前去除标点符号。

编辑:刚刚注意到其他事情 - 需要在循环之外完成对空列表的测试。我更新了上面的代码以反映这一点。

于 2013-04-02T19:37:58.103 回答