2015-05-17 3 views
-1

Для того, чтобы обработать лирику альбома, я сделал constructor: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(this.name, this.lyrics); 
    }; 

Я также создал глобальную переменную для отслеживания лирики:

var globalLyrics = []; 

Затем я создал, скажем, 24 экземплярам песни:

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"]); 

      (...)//all the way to: 

var song24 = new Song('Lab', 'Buffalo', 23, '3:10', 'Me and The Plant', 
     ["this", "tambourine", "is", "waging", "a", "war", "will", 
     "drecnched", "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 = ["this", "tambourine", "is"]; 

Я сделал метод как для подсчета пересечений между входом со словами Текст песни:

Song.prototype.countIntersect = function(input) { 

var lyrics = this.lyrics; 
var count = 0; 
var temp = []; 
for(var i = 0; i < input.length; i++){ 
    for(var k = 0; k < lyrics.length; k++){ 
     if(input[i] == lyrics[k]){ 
      count += 1; 
      temp.push(input[i]); 
      break; 
     } 
    } 
} 
return count; 

}

ВОПРОС:

Я хочу создайте function, способный перебирать ВСЕ песню instances, возвращая название песни, которая имеет максимальное количество слов intersections с input.

Должен ли я сделать трекер с intersectioncounts для всех instances из this.lyrics, а затем вернуть песню, соответствующую наибольшему count?

DESIRED ОТВЕТ: Учитывая input пример, после создания этого нового prototypefunction, я хотел бы, чтобы он перебирая все тексты песен и возвращением // «Буффали», имя song24.

ответ

0
for (key in var) { 
    // this will skip native keys and only alert user assigned keys 
    if (!var.hasOwnProperty(key)) continue; 

    alert(key + ':' + var[key]); 
} 

здесь скрипку показывая детали относительно вашего использования: http://jsfiddle.net/aequalsb/xh1t8d9p/

Смежные вопросы