搜索功能有问题

时间:2013-02-20 21:20:51

标签: javascript regex loops match

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

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

1 个答案:

答案 0 :(得分: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");
    }
}

以下是我认为你想要的一个例子:http://jsfiddle.net/sHSdK/2/