使用for循环代替过滤器



创建一个遍历对象数组的函数(首先)参数)并返回具有匹配名称的所有对象的数组和值对(第二个参数)。类的每个名称和值对源对象必须存在于来自集合的对象中它将包含在返回的数组中。

这是在freecodecamp上的一个挑战,我很难使用ONLY for循环为它编写代码。我可以让它与filter()和for循环一起工作,但是我想看看如果我们使用if语句和for循环会怎样。有人能帮我一下吗?

代码:(使用过滤器)

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;
});
}

//input
whatIsInAName([{ "apple": 1, "bat": 2 }, { "apple": 1 }, { "apple": 1, "bat": 2, "cookie": 2 }, { "bat":2 }], { "apple": 1, "bat": 2 })
//output
[{ "apple": 1, "bat": 2 }, { "apple": 1, "bat": 2, "cookie":2 }]

不使用过滤器(我的方法):

function whatIsInAName(collection, source) {
let n=[]
arrayOfSrc=Object.keys(source) // contains the array of properties of source
for(let obj of collection){
for(let propName of arrayOfSrc){
//if obj hgas the property and the value of the property also matches
if(obj.hasOwnProperty(propName) && source[propName]==obj[propName]){
//push the matched object to n
n.push(obj)
}
}
}
console.log(n)
return n

}

请使用此代码。

let result=[]
arrayOfSrc=Object.keys(source)
for(let obj of collection){
let count = 0;
for(let propName of arrayOfSrc){
if(obj.hasOwnProperty(propName) && source[propName]==obj[propName]){
count++;
}
}
if(result.indexOf(obj) == -1 && count == arrayOfSrc.length) result.push(obj)
}
return result

最新更新