2017-07-08 76 views
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

+0

無需遍歷所有的對象鍵...只使用[對象#hasOwnProperty()](HTTPS:/ /developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty) – charlietfl

回答

1

Object原型不定義length功能,這就是爲什麼它是undefined。但是,您可以使用Object.keys得到您的每一個對象(自己)屬性鍵的數組:

var props = Object.keys(contracts[i]); 

for (var j = 0; j < props.length; j++) { 
    // etc. 
}