如何调试这个艺术代码你呢?

时间:2017-06-18 18:28:56

标签: javascript

这是算法挑战

  

创建一个查看对象数组(第一个参数)的函数,并返回具有匹配的属性和值对(第二个参数)的所有对象的数组。如果要包含在返回的数组中,源对象的每个属性和值对都必须存在于集合中的对象中。

我写过这个,但在某些情况下会出错。这段代码有什么问题?

function whatIsInAName(collection,source) {
   var ks = Object.keys(source);
   var vals = [];
   var arr = [];
   var counter = ks.length;

   for(var k in source) {
      vals.push(source[k]);
   }

    for(var i = 0; i < collection.length; i++) {
      for(var j = 0; j < counter; j++) {
           if(collection[i].hasOwnProperty(ks[j]) && collection[i][ks[j]] === vals[j]) {
               arr.push(collection[i]);
           }
         }
      }

  return arr;

}

功能调用&amp;返回值

(1)致电:

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

(1)返回:(正确)

[{ first: "Tybalt", last: "Capulet" }] 

(2)致电:

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

(2)返回:(正确)

[{ "a": 1 }, { "a": 1 }, { "a": 1, "b": 2 }] 

(3)致电:

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

(3)返回:(不正确)

[{"a":1,"b":2}, {"a":1,"b":2}, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }, { "a": 1, "b": 2, "c": 2 }] 

(4)致电:

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

(4)返回:(不正确)

[{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }, { "a": 1, "b": 2, "c": 2 }] 

3 个答案:

答案 0 :(得分:0)

function whatIsInAName(collection, object) {
    var passValue = Object.keys(object).length;
    var counter = 0;
    var correctObjects = [];
    for (var i = 0; i < collection.length; i++) {
        var currentObject = collection[i];
        counter = 0

        for (var key in currentObject) {
            var currentValue = currentObject[key];
            if (object[key] === currentValue) {
                counter++;
            }
        }

        if (counter === passValue) {
            correctObjects.push(currentObject);
        }
    }

    return correctObjects;
}

首先迭代数组,然后检查每个值。

答案 1 :(得分:0)

问题是,当您找到匹配的元素时,您没有突破内部for循环。这会导致在源中多次匹配的集合中的任何元素将重复添加到结果数组中。  您可以通过添加break;

来解决此问题
arr.push(collection[i]);
break;

答案 2 :(得分:0)

        function whatIsInAName(collection, source) {
          const argKeys = Object.keys(source);

            return collection.filter(function(obj) {
              return argKeys.every(function(key) {
                return obj.hasOwnProperty(key) && obj[key] === source[key];
              });
            });
         }