工作,你的鍛鍊,我這樣做是要求一個練習:過濾不人哪領域中Freecodecamp
製作,看起來通過對象(第一個參數)的陣列功能,並返回數組所有具有匹配屬性和值對的對象(第二個參數)。源對象的每個屬性和值對必須存在於集合中的對象中(如果它將包含在返回的數組中)。
我試圖做創建此:
function whatIsInAName(collection, source) {
// What's in a name?
var arr = [];
// Only change code below this line
var srcKeys = Object.keys(source);
arr = collection.filter(function(obj) {
for (var i = 0;i < srcKeys;i++) {
return obj.hasOwnProperty(srcKeys[i]) || obj[srcKeys[i]] == source[srcKeys[i]];
}
});
// Only change code above this line
return arr;
}
whatIsInAName([
{ first: "Romeo", last: "Montague" },
{ first: "Mercutio", last: null },
{ first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
然而,這將返回一個空數組。我想也許我並不完全瞭解過濾方法的功能。
一個上市的解決方案是:
function whatIsInAName(collection, source) {
// "What's in a name? that which we call a rose
// By any other name would smell as sweet.」
// -- by William Shakespeare, Romeo and Juliet
var srcKeys = Object.keys(source);
// filter the collection
return collection.filter(function (obj) {
for(var i = 0; i < srcKeys.length; i++) {
if(!obj.hasOwnProperty(srcKeys[i]) || obj[srcKeys[i]] !== source[srcKeys[i]]) {
return false;
}
}
return true;
});
}
// test here
whatIsInAName([
{ first: "Romeo", last: "Montague" },
{ first: "Mercutio", last: null },
{ first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
請儘量詳細解釋,以幫助像我這樣的小白明白爲什麼我做了什麼不給輸出給定答案:(
相同萬分感謝您的幫助。