0
我试图重写_.where(),这是否:试图重写下划线库_.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在年底返回。
首先,在函数中定义'newArr',而不是在外面。其次,请注意,您比较了这些对象,那么简单的'==='将不起作用。 – raina77ow 2014-10-11 20:46:12
好的 - 生病添加newArr的FX,但我不知道如何改变范围将在这里有所作为?我如何访问对象值本身? – rahul2001 2014-10-11 21:00:35
要遍历对象的属性,请使用['for ... in'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in)和['hasOwnProperty'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty)来检查它是对象的属性而不是更下层的对象原型链。 – 2014-10-12 10:50:34