javascript-对象搜索算法挑战

对象搜索算法挑战

function where(collection, source) {
var arr = [];
var status = null;
// What's in a name?
for (var i = 0; i < collection.length; i++) {
    for(var imp in source){
        if (source[imp] !== collection[i][imp]) {
            status = 0;
            break;
        }
        status = 1;
    }
    if(status == 1){
        arr.push(collection[i]);
    }
}
return arr;
}

where([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });

这样写会不会比使用下面这种好点

function where(collection, source) 
{ var arr = [], index = 0; // What's in a name? 
// console.log(Object.getOwnPropertyNames(source).length); 
//获取对象属性个数 
for (; index < collection.length; index++) { 
    for (var key in collection[index]) { 
        var count = 0; 
        for (var key2 in source) { 
            if (collection[index].hasOwnProperty(key2)) { 
                if (source[key2] == collection[index][key2]) { 
                    count++; 
                } 
                if (count == Object.getOwnPropertyNames(source).length && key == key2) { 
                    arr.push(collection[index]); 
                } 
            } 
        } 
    } 
} 
return arr; 
}
原文地址:https://www.cnblogs.com/wwjchina/p/9491890.html