我正试图编写一个函数,该函数查找对象数组(第一个参数)并返回包含给定对象(第二个参数)的所有键/值对的对象数组。
我的代码仅在
如何处理
我的代码仅在
source
对象(第二个参数)包含一个键/值对时起作用。当 source
对象有两个或更多的键/值对时,结果不如预期。如何处理
source
对象中超过一个键/值对的情况?function findObjects(collection, source) {
var result = [];
for (i=0; i<collection.length; i++) {
for (var prop in source) {
if (collection[i].hasOwnProperty(prop) && collection[i][prop] == source[prop]) {
console.log('Collection\'s object ' + [i] + ' contains the source\'s key:value pair ' + prop + ': ' + source[prop] + '!');
result.push(collection[i]);
} else {
console.log('fail');
}
}
}
console.log('The resulting array is: ' + result);
return result;
}
findObjects([{ "a": 1, "b": 2 }, { "a": 1 }, { "b": 2, "c": 2 }], { "a": 1, "b": 2 });
// only the first object should be returned since it contains both "a":1 and "b":2
return
语句,我不明白正在发生什么。如果你有时间,能否解释一下你的答案是怎么工作的?即,为什么它可以运行? - Brian Zelip(c)
和(k)
分别从哪里传递过来的? (感谢您的有用补充意见。) - Brian Zelipc
和k
是参数。 - Nina Scholzcollection
数组只有可枚举属性的对象,而source
对象只有属性作为可枚举属性,所以JavaScript通过排除法知道要传递什么参数,因为没有其他可以作为参数传递的东西吗?编辑 因为c
代表collection
中的每个对象,k
代表source
中的每个属性,对吗? - Brian Zelipc
是collection
的一个元素,而k
是source
的键(即keys
的元素)。无论是 ES5 还是 ES6 的两个部分都完全相同。 - Nina Scholz