2013-02-20 130 views
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); 
    } 
} 

這是一個搜索功能,我試圖將用戶在搜索欄中鍵入的內容與我之前在代碼中創建的對象進行匹配。它們必須與我給予對象的「誰」和「任務」參數相匹配。所以一個對象是誰:簡任務:做點什麼,另一個是誰:斯科特任務:得到牛奶。問題是,在我最後的警報中,我只能匹配斯科特而不是簡。斯科特是我添加的最後一個。有什麼方法我需要修改我的循環或更改我的搜索條件?搜索功能故障

回答

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/

+1

此外,一個新的正則表達式的創作可能是外for循環,我認爲 – albertoblaz 2013-02-20 21:36:15

+1

@albertoblaz是的,我注意到了。使用'新的RegExp'而不是'/ stuff /'的一個棘手的事情是它使用循環很奇怪。我想我必須在循環中設置'lastIndex'屬性,每次我想聲明一次。我正在尋找,並計劃更新:) – Ian 2013-02-20 21:38:53

+0

非常感謝你 – user2084813 2013-02-20 21:39:38