简体   繁体   中英

how to fix 'Cannot read property of undefined'?

I'm trying to determine which object in an array has the longest name and logging that object to the console.

I can't seem to access the length of the name property in my if statement.

const instructorWithLongestName = function(instructors) {
  let longest;
  for (let i = 0; i < instructors.length; i++) {
    if (instructors[i].name.length > longest.length) {
      longest = instructors[i];
    }
  }
  return longest;
};

console.log(instructorWithLongestName([
  {name: "Samuel", course: "iOS"},
  {name: "Jeremiah", course: "Web"},
  {name: "Ophilia", course: "Web"},
  {name: "Donald", course: "Web"}
]));
console.log(instructorWithLongestName([
  {name: "Matthew", course: "Web"},
  {name: "David", course: "iOS"},
  {name: "Domascus", course: "Web"}
]));

I expect the output of
{name: "Jeremiah", course: "Web"}
{name: "Domascus", course: "Web"}

but I get an error stating it cannot read property '.length'

You could use

let longest = Number.MIN_SAFE_INTEGER;

to set longest to the smallest safe integer , since minimum length is equal to 0 (number elements of elements is equal to zero)
Or simply set it to 0 :

let longest = 0

One tiny 'remark' - as @Jaromanda X mentioned in a comment - let without providing a value will result in undefined , eg:

let test1;
let test2 = 'some random string';
let test3 = 4;

// comments represent output of corresponding command  
console.log(test1); // undefined
console.log(test2); // some random string
console.log(test3); // 4

Thanks for the help guys! By changing longest to the first object and starting my loop at 1 I was able to call the correct properties.

const instructorWithLongestName = function(instructors) {
  let longest = instructors[0];
  for (let i = 1; i < instructors.length; i++) {
    if (instructors[i].name.length > longest.name.length) {
      longest = instructors[i];
    }
  }
  return longest;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM