我已经看了这个并阅读了一段时间,但似乎无法理解。我确信这很简单,但我不明白为什么我可以访问集合中的数据。我收到错误
test undefined
如果我移出 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" });
最佳答案
在您的代码中,Object.values 返回的是“Capulet”的 source 值,而在 for 循环中,您将 source 等同于数组(source 是对象),这就是为什么 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" });
关于javascript - 访问数组中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42641574/