FreeCodeCampChina / freecodecamp.cn

FCC China open source codebase and curriculum. Learn to code and help nonprofits.

Home Page:https://fcc.asia/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

why: TypeError: Cannot read property 'firstName' of undefined

oldwang-ai opened this issue · comments

Challenge Profile Lookup has an issue.
User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36.
Please describe how to reproduce this issue, and include links to screenshots if possible.

My code:

//初始化变量
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 lookUp(firstName, prop){
// 请把你的代码写在这条注释以下
  var i = 0;
  while (contacts[i++].firstName) {
    if (contacts[i].firstName === firstName) {
      if (contacts[i][prop]) {
        return contacts[i][prop];
      } else {
        return "No such property";
      }
    }
  }
  return "No such contact";
// 请把你的代码写在这条注释以上
}

// 你可以修改这一行来测试你的代码
lookUp("Akira", "likes");

i 初始值设置为 -1,然后 while(contacts[++i]) 就可以了
你现在的写法逻辑是:

  1. 判断 contacts[i].firstName 是否存在
  2. 执行 i += 1
    因此,你是判断当前的,然后用下一个 i 进入循环体
    所以如果 contacts[i + 1]undefined(即 i 为数组长度),那么尝试访问 .firstName 就会报错