Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/379.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript-原型内部未定义_Javascript - Fatal编程技术网

javascript-原型内部未定义

javascript-原型内部未定义,javascript,Javascript,我有一个构造器: 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(th

我有一个构造器:

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;
}

但我得到“歌曲未定义”。错误必须出现在
原型函数中。我错过了什么?谢谢。

您正在创建24首具有可变名称的歌曲
song1
song2
,等等。但是,稍后当您尝试访问它们时,您正在使用名为
song
的不存在数组查找歌曲。你可以先定义一组歌曲来解决这个问题。这也意味着您不需要确切知道代码中有多少首歌曲。您可以根据外部源(如数据库、公共API或用户输入)动态添加或删除歌曲

var-songs=[];
//像这样添加你的歌曲
歌曲。推送(新歌(/*…*/);
另外,您的
currentSong
变量是一个数组,其中包含一个song变量名称字符串。如果将歌曲存储在数组中,则可以只存储索引或实际歌曲

Song.prototype.songIntersect=函数(输入){
var-bestSong=null;
var bestCount=-无穷大;
for(歌曲中的var i){
var currentCount=setIntersection(歌曲[i]。歌词,输入)。长度;
如果(currentCount>best.count){
最佳歌曲=歌曲[我];
最佳计数=当前计数;
}
}
返回bestSong&&bestSong.name;
}

您如何调用
songIntersect()
以及错误在哪一行代码上?好吧,我想我已经见过三次这个问题了。这是同一个人吗,如果您愿意,我可以一对一地帮您吗?您已经在循环播放所有歌曲了,当前计数不应该是这个吗<代码>var currentCount=setIntersection(宋词[i],输入)。长度
在使用prototype定义之前,您似乎调用了
songIntersect()
。您需要使用不同的方法,基于信息外观,您正在以奇怪的方式尝试。
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;
}