0
//Setup
var contacts = [
{
"firstName": "Akira",
"lastName": "Laine",
"number": "0543236543",
"likes": ["Pizza", "Coding", "Brownie Points"]
},
{
"firstName": "Harry",
"lastName": "Potter",
"number": "0994372684",
"likes": ["Hogwarts", "Magic", "Hagrid"]
},
{
"firstName": "Sherlock",
"lastName": "Holmes",
"number": "0487345643",
"likes": ["Intriguing Cases", "Violin"]
},
{
"firstName": "Kristian",
"lastName": "Vos",
"number": "unknown",
"likes": ["Javascript", "Gaming", "Foxes"]
}
];
function lookUpProfile(firstNames, prop){
// Only change code below this line
for (var i=0; i<contacts.length; i++){
if(contacts[i].firstName == firstNames){
for (var j=0; j<contacts[i].length; j++){
if(contacts[i][j] == prop){
return contacts[i][j].prop;
} else {
return "No such property";
}
}
} else{
return "No such contact";
}
}
// Only change code above this line
}
// Change these values to test your function
lookUpProfile("Akira", "likes");
上面的代碼不工作,特別是在與for (var j=0; j<contacts[i].length; j++)
線路的線路,如contacts[i].length
是不確定的,當我跑console.log
陳述了我的代碼搶嵌套Objects.length對象的JavaScript內
你究竟如何定義嵌套在另一個對象內部的javascript對象的長度?
參考例https://www.freecodecamp.org/challenges/profile-lookup
無需遍歷所有的對象鍵...只使用[對象#hasOwnProperty()](HTTPS:/ /developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty) – charlietfl