因此,我在freecodecamp上遇到了一些問題,我被困在一個說: 「使一個函數看起來通過一個對象數組(第一個參數)並返回一個包含所有對象的數組具有匹配的屬性和值對(第二個參數)「。所以,我看着的答案,來到翻過下一代碼:瞭解函數的返回值
function whatIsInAName(collection, source) {
var arr = [];
var keys = Object.keys(source);
// Filter array and remove the ones that do not have the keys from source.
arr = collection.filter(function(obj) {
return keys.every(function(key) {
return obj.hasOwnProperty(key) && obj[key] === source[key];
});
});
return arr;
}
才明白什麼做什麼,我不能似乎得到的是collection.filter內的回報,爲什麼我們需要這兩個:
return keys.every(function(key) {
return obj.hasOwnProperty(key) && obj[key] === source[key];
爲什麼代碼不能只用第二個。
有人可以向我解釋這一點。
它可以工作,沒有'hasOwnProperty',但如果對象的祖先有屬性,這些也將被考慮給孩子。 –
因爲您需要使用'return'從函數返回一個值。第一個返回從傳遞給'every'的函數返回。第二個回報是從'whatIsInAName'返回的。 – Carcigenicate
閱讀https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty,瞭解關於該方法的更多詳細信息。 –