2011-11-05 80 views
0

如何計算記錄字段中的模式並創建它的數組?計算記錄字段中的模式並創建數組

例如:

(使用我下面的例子)在搜索中目前給我的

0 0 (**in** seen at index 0 of book 0 title record) 

0 13 (**in** seen at index 13 of book 0 title record) 

1 19 (**in** seen at index 0 of book 1 title record) 

2 -1 (**in** not seen at any index of title record) 

多個輸出理想的情況下,我想代碼返回:

2,1,0 (**in** seen 2 times in book 0 title record, **in** seen 1 time in 
book 1 title record and **in** not seen in book 2 title record 

提前致謝!

books = [ 
    { 
    title: "Inheritance: Inheritance Cycle, Book 4", 
    author: "Christopher Paolini", 
    }, 
{ 
    title: "The Sense of an Ending", 
    author: "Julian Barnes"}, 
{ 
    title: "Snuff Discworld Novel 39", 
    author: "Sir Terry Pratchett", 
    } 
] 
search = prompt("Title?"); 

function count(books, pattern) { 
    if (pattern) { 
     var num = 0; 
     var result = []; 
     for (i = 0; i < books.length; i++) { 
      var index = books[i].title.toLowerCase().indexOf(pattern.toLowerCase()); 
      do { 
       alert(i + " " + index); 
       index = books[i].title.toLowerCase().indexOf(pattern.toLowerCase(), index + 1); 
      } 
      while (index >= 0) 
      num = 0; 
     } 
     return result; 
    } 
    else { 
     return ("Nothing entered!"); 
    } 
} 
alert(count(books, search)); 
+0

[正則表達式] [1]在這裏可能是合適的。 [1]:http://stackoverflow.com/questions/1072765/count-number-of-matches-of-a-regex-in-javascript –

回答

1

使用String.prototype.match,則返回匹配的數組(或者如果有沒有空),數組的長度告訴你有多少場比賽有。例如

var books = [ 
    { 
    title: "Inheritance: Inheritance Cycle, Book 4", 
    author: "Christopher Paolini", 
    }, 
{ 
    title: "The Sense of an Ending", 
    author: "Julian Barnes"}, 
{ 
    title: "Snuff Discworld Novel 39", 
    author: "Sir Terry Pratchett", 
    } 
]; 
var result = []; 
var re = /in/ig; 
var matches; 
for (var i=0, iLen=books.length; i<iLen; i++) { 
    matches = books[i].title.match(re); 
    result.push(matches? matches.length : 0); 
} 
alert(result);