freeCodeCamp中一些有趣的方法

1. 过滤对象(找到数组中(collection)与之(source)匹配对象,过滤掉数组中(collection)不匹配对象)

 1 function where(collection, source) {
 2   var arr = [];
 3   var keys = Object.keys(source);
 4   arr = collection.filter(function(item){
 5     for (var i = 0; i < keys.length; i++) {
 6       if ( !item.hasOwnProperty(keys[i]) || item[keys[i]] !== source[keys[i]]) {
 7         return false;
 8       }
 9     }
10     return true;
11   });
12   // What's in a name?
13   
14   return arr;
15 }
16 
17 where([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });

 

posted @ 2018-11-23 09:48  正在变厉害的路上  阅读(486)  评论(0编辑  收藏  举报