大家好,我想在这里解决这个问题
创建一个通过列表(第一个参数)查找并返回的函数
具有相等属性值(第二个对象)的所有对象组成的数组
论点)。
但是如果我的生活取决于它,我似乎无法遍历对象数组......这是我的以下代码
function where(collection, source) {
for(var prop in collection){
if(collection.hasOwnProperty(prop)){
console.log("collection." + prop + "=" + collection[prop]);
}
}
}
where([{ first: 'Romeo', last: 'Montague' }, { first: 'Mercutio', last: null }, { first: 'Tybalt', last: 'Capulet' }], { last: 'Capulet' });
我正在阅读有关hasOwnProperty方法和in循环中的文档,但似乎我在错误地利用它们,感谢任何指导。
这不是重复的
最佳答案
The for...in
loop is not what you want for iterating over arrays in javascript。
使用顺序for循环遍历数组,使用for..in
循环遍历对象的键...
for(var i=0; i<collections.length; i+=1) {
for(var prop in collections[i]){
if(collections[i].hasOwnProperty(prop)){
console.log("collection." + prop + "=" + collections[i][prop]);
}
}
}