为什么For循环解决方案与.Every()解决方案不同?

时间:2017-06-25 03:25:32

标签: javascript arrays

这是针对FreeCodeCamp的挑战:“因此你是艺术家”。挑战要求“创建一个查看对象数组(第一个参数)的函数,并返回具有匹配的属性和值对(第二个参数)的所有对象的数组。”

我必须查看解决方案才能了解它的工作原理。我还使用 For 循环制作了自己的解决方案,看看它是否也能正常工作。

使用这个参数/数组:“whatIsInAName([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "b": 2 })”应返回“[{ "a": 1, "b": 2 }, { "a": 1, "b": 2, "c": 2 }]”,似乎.Every()方法只能起作用。

。每种方法

function whatIsInAName(collection, source) {
  // What's in a name?
  var arr = [];
  // Only change code below this line
  var myCol = collection;
  var mySou = Object.keys(source);
  
  arr =  myCol.filter(function(object){
    return mySou.every(function(key){
      return object.hasOwnProperty(key) && object[key] === source[key];
      
    }
    );
  });
  
  // Only change code above this line
  return arr;
}

console.log(whatIsInAName([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "b": 2 }));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

对于循环方法

function whatIsInAName(collection, source) {
  // What's in a name?
  var arr = [];
  // Only change code below this line
  var myCol = collection;
  var mySou = Object.keys(source);
  
  arr =  myCol.filter(function(object){
    
      for (var i = 0; i < mySou.length; i++) {
        return object.hasOwnProperty(mySou[i]) && object[mySou[i]] === source[mySou[i]];
        
    }
    
  });
  
  // Only change code above this line
  return arr;
}

console.log(whatIsInAName([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "b": 2 }));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

两个问题。 For 循环方法是否可以工作?如果是,那么我如何才能让它只返回“[{ "a": 1, "b": 2 }, { "a": 1, "b": 2, "c": 2 }]

1 个答案:

答案 0 :(得分:1)

您可以在过滤器功能中添加两个条件,如下所示:

function whatIsInAName(collection, source) {
  // What's in a name?
  var arr = [];
  // Only change code below this line
  var myCol = collection;
  var mySou = Object.keys(source);

  arr =  myCol.filter(function(object){

      for (var i = 0; i < mySou.length; i++) {
        if(!(object.hasOwnProperty(mySou[i]) && object[mySou[i]] === source[mySou[i]])){
            return false;         # if any key value pair in the source doesn't exist in 
                                  # object, return false
        };
    }
    return true;   # if all key value pairs in the source can be found in the object return true
  });

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

whatIsInAName([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "b": 2 })
# [ { a: 1, b: 2 }, { a: 1, b: 2, c: 2 } ]