在对象内部抓取嵌套的Objects.length Javascript

时间:2017-07-08 14:17:59

标签: javascript arrays json object

//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语句运行到我的代码中时

您究竟如何定义嵌套在另一个对象中的javascript对象的长度?

参考示例https://www.freecodecamp.org/challenges/profile-lookup

1 个答案:

答案 0 :(得分:1)

std::vector<std::complex<double> >原型未定义Object函数,这就是length的原因。但是,您可以使用undefined

在对象中获取每个(自己的)属性键的数组
Object.keys