这个问题已经在这里有了答案:

//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++)行的行上,因为当我运行console.log时, contacts[i].length是未定义的我的代码中的语句

您如何精确定义嵌套在另一个对象内部的javascript对象的长度?

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

===============>>#1 票数:1

Object原型未定义length函数,因此undefined它。 但是,您可以使用Object.keys对象中每个(自有)属性键的数组:

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

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

  ask by Vincent Tang translate from so

未解决问题?本站智能推荐: