javascript - 遍历对象的所有实例

时间:2015-05-17 04:58:38

标签: javascript

为了处理相册的歌词,我制作了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;
    globalLyrics.push(this.name, this.lyrics);
    };

我还创建了一个全局变量来跟踪歌词:

    var globalLyrics = [];

然后我为Song创建了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最多的歌曲的名称。< / p>

我是否必须为所有intersection counts制作instances this.lyrics跟踪器,然后返回与最大count对应的歌曲?

期望的答案:给定input示例,在创建新的prototype function之后,我想让它迭代所有歌词并返回//'Buffalo',这个名字这首歌24。

1 个答案:

答案 0 :(得分: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/

相关问题