JavaScript custom search function not working in IE
Hi i am trying to create a custom search for a json array
My code works fine in chrome and firfox but not in ie.
the code works as follows. It loops trough each search term 'needle' and if it finds the word in the question it adds it to the array. if it finds a different search term in the same question is the hit counter gets incremented.
All the code is here and can be run.
The error i get is:
Line:24
Char:3
Error:qna_questions[..].q is null or not an object
qna_questions = [
{ 'q':'this is a very good question','id':'1'},
{ 'q':'i like pllo in the summer','id':'2'},
{ 'q':'it rains allot in the summer mushroom','id':'3'},
{ 'q':'i love people and straberry cake','id':'4'},
{ 'q':'i love people and berry rain','id':'5'},
{ 'q':'dsff sd fsd rains sdfsd fsd ','id':'6'},
{ 'q':'the dog is fat','id':'7'},
];
var search_result = new Array();
var needle = "dog fat summer allot mushroom";
var needle = needle.split(' ');
for(j = 0; j < qna_questions.length; j++) {
for(i =0; i < needle.length; i++) {
if(qna_questions[j].q.search(needle[i].toLowerCase()) != -1 ) {
if( search_result[qna_questions[j].id] === undefined ) {
search_result[qna_questions[j].id] = {
开发者_如何学编程 'q':qna_questions[j].q,
'id':qna_questions[j].id,
'hits':0
};
} else {
search_result[qna_questions[j].id].hits++;
}
}
}
}
search_result.sort(function(a,b) { return parseInt(b.hits) - parseInt(a.hits) } );
for (x in search_result)
{
alert(search_result[x].q + ": "+search_result[x].hits +"<br />");
}
qna_questions = [
{ 'q':'this is a very good question','id':'1'},
{ 'q':'i like pllo in the summer','id':'2'},
{ 'q':'it rains allot in the summer mushroom','id':'3'},
{ 'q':'i love people and straberry cake','id':'4'},
{ 'q':'i love people and berry rain','id':'5'},
{ 'q':'dsff sd fsd rains sdfsd fsd ','id':'6'},
{ 'q':'the dog is fat','id':'7'},
];
Note the extra comma at the end of qna_questions ... in IE that will be one more null entry at the end of the array.... remove the comma and you should be good.
qna_questions = [
{ 'q':'this is a very good question','id':'1'},
{ 'q':'i like pllo in the summer','id':'2'},
{ 'q':'it rains allot in the summer mushroom','id':'3'},
{ 'q':'i love people and straberry cake','id':'4'},
{ 'q':'i love people and berry rain','id':'5'},
{ 'q':'dsff sd fsd rains sdfsd fsd ','id':'6'},
{ 'q':'the dog is fat','id':'7'}
];
精彩评论