【发布时间】:2014-12-06 18:49:22
【问题描述】:
我正在尝试重写执行此操作的 _.where():
where_.where(列表,属性) 遍历列表中的每个值,返回包含属性中列出的所有键值对的所有值的数组。
我无法访问作为属性传递给 where() 的数组中的不同对象。如何访问数组中对象的值并对其进行迭代?
这就是我所拥有的:
var arr = [{title: "Cymbeline", author: "Shakespeare", year: 1611},
{title: "The Tempest", author: "Shakespeare", year: 1611},
{title: "Cymbeline", author: "steve", year: 1671}];
var newArr = [];
var where = function (list, properties) {
for (var i = 0; i < list.length; i++){
console.log(list[i]); // just gives the array again??
if (list[i] == properties) {// this conditional should compare the values in arr and properties
newArr.push(list[i]); // if the values in arr match those in properties then the respective objects get pushed to newArr
}
}
return newArr;
}
console.log(where(arr, {author: "Shakespeare", year: 1611}));
当最后返回 newArr 时,我最终得到的是 arr[] 和一个空的“[]”。
【问题讨论】:
-
首先,在函数内部而不是外部定义
newArr。其次,注意你比较对象,这么简单的===是行不通的。 -
好的 -- 将 newArr 添加到 fxn 但我不知道更改范围将如何产生影响?我如何访问对象本身的值?
-
要遍历对象的属性,请使用
for...in和hasOwnProperty来检查它是对象的属性,而不是原型链下游的对象。
标签: javascript arrays object functional-programming underscore.js