이 생성자가 있습니다.
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;
}
하지만 "정의되지 않은 노래"가 표시됩니다. 오류는 prototype function
. 내가 여기서 뭘 놓치고 있니? 감사합니다.
당신은 변수 이름으로 24 곡을 만드는 song1
, song2
등 그러나 액세스를 시도 할 때 나중에, 당신은 이름이 존재하지 않는 배열을 사용하여 노래를 찾고 있습니다 song
. 먼저 노래 배열을 정의하여이 문제를 해결할 수 있습니다. 이것은 또한 코드에 얼마나 많은 노래가 있는지 정확히 알 필요가 없음을 의미합니다. 데이터베이스, 공용 API 또는 사용자 입력과 같은 외부 소스를 기반으로 노래를 동적으로 추가하거나 제거 할 수 있습니다.
var songs = [];
// add your songs like this
songs.push(new Song(/* ... */));
또한 currentSong
변수는 노래 변수 이름의 문자열을 포함하는 배열입니다. 노래를 배열에 저장하는 경우 색인이나 실제 노래를 대신 저장할 수 있습니다.
Song.prototype.songIntersect = function(input) {
var bestSong = null;
var bestCount = -Infinity;
for (var i in songs) {
var currentCount = setIntersection(songs[i].lyrics, input).length;
if (currentCount > best.count) {
bestSong = song[i];
bestCount = currentCount;
}
}
return bestSong && bestSong.name;
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다