0
function Todo(id, task, who, dueDate) {
    this.id = id;
    this.task = task;
    this.who = who;
    this.dueDate = dueDate;
    this.done = false;
}    

// more code that adds the todo objects to the page and to the array todos

function search() {
    for (var i = 0; i < todos.length; i++) {
        var todoObj = todos[i];
        console.log(todoObj.who); //shows both jane and scott
        console.log(todoObj.task); // shows both do something and get milk
    }
    var searchTerm = document.getElementById("search").value;
    searchTerm = searchTerm.trim();
    var re = new RegExp(searchTerm, "ig");
    var results = todoObj.who.match(re);
    if (searchTerm == null || searchTerm == "") {
        alert("Please enter a string to search for");
        return;
    } else {
        alert(results);
    }
} 

这是一个搜索功能,我试图将用户在搜索栏中输入的内容与我之前在代码中创建的对象进行匹配。它们必须与我为对象提供的“谁”和“任务”参数相匹配。所以一个对象是谁:简任务:做某事,另一个对象是谁:斯科特任务:拿牛奶。问题是,在我上次的警报中,我只能匹配 scott 而不是 jane。斯科特是我添加的最后一个。有什么方法我需要修改我的循环或更改我的搜索条件吗?

4

1 回答 1

1

您的问题是您正在遍历这些项目,然后todoObj在该循​​环之后使用。所以todoObj只会保存数组中的最后一项。你需要重新组织一下......尝试这样的事情:

function search() {
    var searchTerm = document.getElementById("search").value;
    searchTerm = searchTerm.trim();

    if (searchTerm == null || searchTerm == "") {
        alert("Please enter a string to search for");
        return;
    } else {
        var todoObj = undefined,
            results = undefined,
            re = new RegExp(searchTerm, "ig");

        for (var i = 0; i < todos.length; i++) {
            todoObj = todos[i];
            results = todoObj.who.match(re);
            if (results) {
                alert("You found " + todoObj.who + ", who needs to " + todoObj.task + " by " + todoObj.dueDate);
                return;
            }
            console.log(re.lastIndex);
        }

        alert("You didn't match anyone");
    }
}

Here's an example of it working as I think you want it to: http://jsfiddle.net/sHSdK/2/

于 2013-02-20T21:33:12.727 回答