我有这个构造函数:
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;
globalLyrics.push(this.lyrics);
};
然后我创建了24个实例,直到:
var song24 = new Song('Lab', 'Buffalo', 23, '3:10', 'Band',
["this", "tambourine", "is", "waging", "a", "war", "will",
"drenched", "in", "blood", "flood", "egg", "shape",
"shaped", "rock", "rocking", "to", "kill", "the", "bull",
"slay", "slain", "by", "dogs", "snakes", "raven", "scorpio",
"lion", "headed", "head", "god", "rise"]);
我希望与用户输入相交,例如......
var input = ["tambourine", "this"];
...与歌词数据库;为此我有一个交叉函数...
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;
}
...和prototype
function
:
Song.prototype.songIntersect = function(input) {
var bestSong = null;
var bestCount = -Infinity;
for (var i = 1; i <= 24; i++) {
var currentSong = ['song' + i];
var currentCount = setIntersection(song[i].lyrics, input).length;
if (currentCount > bestCount) {
bestSong = currentSong;
bestCount = currentCount;
}
}
return bestSong.name;
}
但我得到了#34;歌曲没有定义&#34;。错误必须在prototype function
中。我在这里想念的是什么?谢谢。
答案 0 :(得分:0)
您正在制作24首变量名为T::operator()(T1, T2, T3)
,song1
等的歌曲。但是,以后当您尝试访问它们时,您正在寻找一个歌曲使用名为song2
的不存在的数组。您可以先通过定义一组歌曲来解决这个问题。这也意味着您无需确切知道代码中有多少首歌曲。您可以根据外部源(如数据库,公共API或用户输入)动态添加或删除歌曲。
song
此外,您的var songs = [];
// add your songs like this
songs.push(new Song(/* ... */));
变量是一个数组,其中包含歌曲变量名称的字符串。如果将歌曲存储在数组中,则可以只存储索引或实际歌曲。
currentSong