寫(xiě)一個(gè) function,它遍歷一個(gè)對(duì)象數(shù)組(第一個(gè)參數(shù))并返回一個(gè)包含相匹配的屬性-值對(duì)(第二個(gè)參數(shù))的所有對(duì)象的數(shù)組鸟辅。如果返回的數(shù)組中包含 source 對(duì)象的屬性-值對(duì)柳击,那么此對(duì)象的每一個(gè)屬性-值對(duì)都必須存在于 collection 的對(duì)象中猿推。
例如,如果第一個(gè)參數(shù)是[{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }]捌肴,第二個(gè)參數(shù)是{ last: "Capulet" }蹬叭,那么你必須從數(shù)組(第一個(gè)參數(shù))返回其中的第三個(gè)對(duì)象,因?yàn)樗俗鳛榈诙€(gè)參數(shù)傳遞的屬性-值對(duì)状知。
如果你被難住了秽五,記得使用 Read-Search-Ask編寫(xiě)你自己的代碼。
這是一些對(duì)你有幫助的資源:
where([{ first: "Romeo", last: "Montague" }, { first:
"Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last:
"Capulet" })應(yīng)該返回[{ first: "Tybalt", last: "Capulet" }]饥悴。
where([{ "a": 1 }, { "a": 1 }, { "a": 1, "b": 2 }], { "a": 1 })應(yīng)該返回[{ "a": 1 }, { "a": 1 }, { "a": 1, "b": 2 }]坦喘。
where([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "b": 2 })應(yīng)該返回[{ "a": 1, "b": 2 }, { "a": 1, "b": 2, "c": 2 }]。
where([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "c": 2 })應(yīng)該返回[{ "a": 1, "b": 2, "c": 2 }]西设。
翻譯是翔哦瓣铣?看了5分鐘才知道講的什么鬼。
就是說(shuō)函數(shù)要返回的東東贷揽,必須是包含source棠笑。source是返回參數(shù)的子集。
參考了別人的答案禽绪,暫時(shí)還不太懂蓖救。懂了再寫(xiě)一遍。
function where(collection, source) {
var arr = [];
var a;
// What's in a name?
for(var Isource in source){}
for(var Icollection in collection){
if(collection[Icollection].hasOwnProperty(Isource)&&collection[Icollection][Isource]==source[Isource])
{
a=arr.push(collection[Icollection]);
}
}
return arr;
}
where([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "c": 2 });