【发布时间】:2009-11-28 18:36:18
【问题描述】:
我有以下 javascript 循环遍历记录数组,并提醒在数组中找到的每个字段的匹配数:
mymusic=[{title:"a",artist:"b",artwork:"c",tracks:[{tracktitle:"d",trackmp3:"e"}]}];
tracksArray=[];
trackTitles=[];
var albumScore=0;
var artistScore=0;
var tracksScore=0;
stringToSearchFor="d";
for(i=0;i<mymusic.length;i++){
if((mymusic[i].title).match(stringToSearchFor))
albumScore+=1;
}
if(albumScore!=0)
alert(albumScore+" match(es) found in Albums");
else
alert("No matches found in Albums");
for(d=0;d<mymusic.length;d++){
if((mymusic[d].artist).match(stringToSearchFor))
artistScore+=1;
}
if(artistScore!=0)
alert(artistScore+" match(es) found in Artists");
else
alert("No matches found in Artists");
for(f=0;f<mymusic.length;f++){
tracksArray[f]=mymusic[f].tracks;
for(g=0;g<tracksArray;g++){
trackTitles[g]=tracksArray[g].tracktitle;
}
for(h=0;h<trackTitles.length;h++){
if(trackTitles(h).match(stringToSearchFor))
{
tracksScore+=1;
}
}
}
if(tracksScore!=0)
alert(tracksScore+" match(es) found in Tracks");
else
alert("No matches found in Tracks");
这适用于“标题”和“艺术家”记录,但对于“曲目”记录,即使存在匹配项,也会始终提示“未找到匹配项”。我想问题在于通过 trackTitles 数组的嵌套 for 循环,但我看不出我可以改变什么来使它工作。有任何想法吗? 谢谢
【问题讨论】:
-
下次将其拆分为方法。这段代码看起来不可读:(
标签: javascript arrays search