我一直在看这个并阅读一段时间,但似乎无法理解。我确信它很简单,但我无法弄清楚为什么我可以访问集合中的数据。我收到错误
测试未定义
如果我移出for循环,我可以正常访问它。我显然缺少一些简单的东西。任何帮助都会很棒。
function whatIsInAName(collection, source) {
// What's in a name?
var arr = [];
// Only change ode below this line
var test = Object.values(source);
for(var i = 0; i < collection.length; i++) {
if (collection[i].test === source[0].test){
arr[i] = collection[i];
}
}
// Only change code above this line
//arr = collection[0].last;
return arr;
}
whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio",
last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
答案 0 :(得分:1)
在你的代码中Object.values返回source的值是“Capulet”,而在for循环中你将source等同为一个数组(source是object),这就是为什么,test是未定义的
function whatIsInAName(collection, source) {
// What's in a name?
var arr = [];
// Only change ode below this line
var test = Object.keys(source);//changes values to keys
console.log(test);
for(var i = 0; i < collection.length; i++) {
if (collection[i][test] === source[test]){ //change how you are accessing test
arr.push(collection[i]);
}
}
// Only change code above this line
//arr = collection[0].last;
console.log(arr);
return arr;
}
whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio",
last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
答案 1 :(得分:0)
您传入的对象没有名为private static class FilteringFlatApplyFunction<T> implements FlatApplyFunction<T,T> {
private final Predicate pred;
LinkedList<T> linkList = new LinkedList<T>();
public FilteringFlatApplyFunction(Predicate<T> p) {
this.pred = p;
this.linkList = linkList;
}
@Override
public List<T> apply(T x){
boolean result = pred.check(x);
if (result = true) {
linkList.add(x);
return linkList;
}
if (result = false) {
linkList = false;
}
return linkList;
}
}
的键。如果您尝试使用此处创建的变量test
,这将无效,因为var test = Object.values(source);
无论如何都是数组。
您可以尝试以下方式:
test
但根据if (collection[i][test] === source[0][test])
test
的值应为Capulet
答案 2 :(得分:0)
试试这个。
function whatIsInAName(collection, source) {
var arr = [];
var keys = Object.keys(source);
for(var i = 0; i < collection.length; i++) {
var item = collection[i];
var all = true;
for(var k = 0; k < keys.length; k++){
var key = keys[k];
if(item[key] != source[key]){
all = false;
break;
}
}
if(all){
arr.push(item)
}
}
return arr;
}