2011-11-05 61 views
0

我一直在幫助朋友改進他的代碼,以便用搜索結果創建一條記錄,而不是創建一個記錄數組,只是返回最後的結果。我如何獲得創建的記錄數組?即尋找將創建一個記錄:從搜索結果中創建記錄陣列

標題:繼承:繼承週期,第4冊 比分:2

標題:結束 分數的意義:1

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) { 
    var result = []; 
    var record = {}; 
    for (i = 0; i < books.length; i++) { 
    var index = -1; 
    result[i] = 0; 
    do { 
     index = books[i].title.toLowerCase().indexOf(pattern.toLowerCase(), index + 1); 
     if (index >= 0) { 
     result[i] = result[i] + 1; 
     record.title = books[i].title; 
     record.score = result[i]; 
     } 
    } while (index >= 0) 
    } 
    return record.title + " " + record.score; 
} 
alert(count(books, search)); 
+2

請縮進代碼。如果它不可讀,很少有人願意嘗試理解它。這次我爲你做了。歡迎來到Stack Overflow! –

回答

1

你應返回result數組,在初始分數爲0時在循環內構建record,在內循環中找到匹配時遞增分數(而不是結果),並且只在得分爲0時纔將record插入result數組不是零:

function count(books, pattern) { 
    var result = []; 
    for (i = 0; i < books.length; i++) { 
    var record = {title: books[i].title, score: 0}; 
    var index = -1; 
    do { 
     index = books[i].title.toLowerCase().indexOf(pattern.toLowerCase(), index + 1); 
     if (index >= 0) { 
     record.score = record.score + 1 
     } 
    } while (index >= 0) 
    if (record.score > 0) { 
     result.push(record); 
    }  
    } 
    return result; 
} 
1

http://jsfiddle.net/Hk7mU/

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", 
    } 
] 



function count(books, pattern) { 
    var results = []; 
    for (var i = 0; i < books.length; i++) { 
    var index = -1; 
    // create a record with zero score 
    var record = {title: books[i].title, score: 0}; 
    do { 
     index = books[i].title.toLowerCase().indexOf(pattern.toLowerCase(), index + 1); 
     if (index >= 0) { 
     // increase score 
     record.score++; 
     } 
    } while (index >= 0) 

    // only add to results if score is greater than zero 
    if(record.score > 0) { 
     results.push(record); 
    } 
    } 
    // return all results 
    // an array containing records 
    return results; 
} 

    search = prompt("Title?"); 
    var searchResults = count(books, search); 
    // loop through result and alert 
    for(var i=0;i<searchResults.length;i++) { 
    alert("Title: " + searchResults[i].title + " Score:" + searchResults[i].score); 
    }