简体   繁体   中英

How to fix TypeError: Cannot read property 'length' of undefined in JavaScript?

I am trying to solve a very easy challenge about finding the longest word in a string. This is the code:

function find(par) {
    let arrayWord = par.split(" ");
    let longestWord = "";
    for (let i = 0; i <= arrayWord.length; i++) {
        if (longestWord.length < arrayWord[i].length) {
            longestWord = arrayWord[i]
        }
    }
    return longestWord;
}
find("Find the longest word");

I would need help understanding why I am getting this error:

Uncaught TypeError: Cannot read property 'length' of undefined at find (:5:47) at:11:1 find @ VM959:5 (anonymous) @ VM959:11

thank you.

Just change condition <= to < and try

 function find(par) { let arrayWord = par.split(" "); let longestWord = ""; for (let i = 0; i < arrayWord.length; i++) { if (longestWord.length < arrayWord[i].length) { longestWord = arrayWord[i] } } return longestWord; } console.log(find("Find the longest word"));

Cannot read property 'length' of undefined comes when it is not able to find variable of certain type(In your case a string) to call the function length. In your case arrayWord[i].length is not a proper string for the last condition of your check as there is no element arrayWord[arrayWord.length] present in the array. That's why arrayWord[i].length is giving you an error for your last iteration. Just change i <= arrayWord.length to i < arrayWord.length

function find(par) {
  let arrayWord = par.split(" ");
  let longestWord = "";
  for (let i = 0; i <arrayWord.length; i++) {
    if (longestWord.length < arrayWord[i].length) {
      longestWord = arrayWord[i]
    }
  }
  return longestWord;
}

Edits: Changes made as suggested by RobG

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