我有constructor
:
var Song = function(side, name, index, duration, author, lyrics) {
this.side = side;
this.name = name;
this.index = index;
this.duration = duration;
this.author = author;
this.lyrics = lyrics
};
我创建了歌曲的实例,例如:
var song1 = new Song('Mithras', 'Wicked', 1, '3:45', 'Me and The Plant',
["politicians", "politician", "politics", "telling",
"lies", "lie", "to", "media", "the", "youngsters",
"young", "elders", "time", "that", "passes", "pass", "by",
"oh", "no", "lie", "detector", "detection", "souls", "as",
"far", "illusion", "goes", "all", "sinners", "sin", "around",
"sun", "earth", "atom", "atoms", "mind", "angels", "angel",
"prophet", "prophets", "martyr", "knives", "elder", "detect",
"shit", "flies", "fly", "meat", "is", "knife", "and", "death",
"life", "I", "am", "gonna", "going", "cast", "a", "sacred",
"circle"]);
我尝试创建prototype
function
以便在用户输入之间创建交叉点,例如...
var input = ["politician", "lies"];
...和歌词:
到目前为止,我有: Song.prototype.songIntersect = function(input){
var lyrics = [song1.lyrics, song2.lyrics, song3.lyrics,
song4.lyrics, song5.lyrics, song6.lyrics,
song7.lyrics, song8.lyrics, song9.lyrics,
song10.lyrics, song11.lyrics, song12.lyrics,
song13.lyrics, song14.lyrics, song15.lyrics,
song16.lyrics, song17.lyrics, song18.lyrics,
song19.lyrics, song20.lyrics, song21.lyrics,
song22.lyrics, song23.lyrics, song24.lyrics];
var count = 0;
for(var i = 0; i < input.length; i++){
for(var k = 0; k < lyrics.length; k++){
for (var n = 0; n < lyrics[k].length; n++){
if(input[i] == lyrics[k][n]){
count += 1;
}
}
}
}
return count;
}
问题:如何跟踪每个歌词的计数,返回最高交叉点数的song.name
?
答案 0 :(得分:1)
将其分成很好的功能:
function setIntersection(a, b) {
var result = [];
for (var i = 0; i < a.length; i++) {
if (b.indexOf(a[i]) !== -1 && result.indexOf(a[i]) === -1) {
result.push(a[i]);
}
}
return result;
}
Song.prototype.songIntersect = function(input) {
var bestSong = null;
var bestCount = -Infinity;
for (var i = 1; i <= 24; i++) {
var currentSong = window['song' + i];
var currentCount = setIntersection(song.lyrics, input).length;
if (currentCount > bestCount) {
bestSong = currentSong;
bestCount = currentCount;
}
}
return bestSong.name;
}