codecamp

对象搜索算法挑战

方法一:

function where(collection, source) {
var arr = [];
  var keys = Object.keys(source);
  arr = collection.filter(function(val){
    for (var i = 0;i < keys.length;i++){
      if(!val.hasOwnProperty(keys[i]) || val[keys[i]] !== source[keys[i]]){
         return false;
         }
    }
    return true;
  });
// What's in a name?
return arr;
}


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

方法二:

function where(collection, source) {
  // What's in a name?
  var arr = [],
      keys = Object.keys(source),
      kLen = keys.length;
  // Only change code below this line
  collection.forEach(function(obj){
    var match = true;
    for(var i=0;i<kLen;i++){
      if(!obj.hasOwnProperty(keys[i])){
        match = false;
        break;
      }else{
        if(source[keys[i]] != obj[keys[i]]){
          match = false;
          break;          
        }
      }
    }
    if(match){
      arr.push(obj);
    }
  });

  
  // Only change code above this line
  return arr;
}


where([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
数字转罗马数字
查询替换算法挑战
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

HTML5&CSS

JavaScript

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }