Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

205
Views
¿Por qué esta implementación de JavaScript para encontrar la palabra más grande devuelve TypeError: no se pueden leer las propiedades de undefined (leyendo 'longitud')

¿Por qué el siguiente código devuelve el error? str es definitivamente una cadena, por lo que no está indefinida. words es una matriz, por lo que llamar a .length también debería ser válido. ¿Qué tiene de malo esta implementación?

TypeError: no se pueden leer las propiedades de undefined (leyendo 'longitud')

 function findLongestWordLength(str) { let words = str.split(" "); let longword = words[0]; for(let i = 0; words.length <= terminal; i++){ if(words[i].length >= longword.length){ longword = words[i] } } let longwordlength = longword.length; return longwordlength; } findLongestWordLength("The quick brown fox jumped over the lazy dog"); // why is this giving the error: TypeError: Cannot read properties of undefined (reading 'length')
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Su condición for es incorrecta. Debería ser si i es más pequeño que el número de palabras, ya que está iterando a través de cada palabra:

 function findLongestWordLength(str) { let words = str.split(" "); let longword = words[0]; for(let i = 0; i < words.length; i++){ if(words[i].length >= longword.length){ longword = words[i] } } let longwordlength = longword.length; return longwordlength; } console.log(findLongestWordLength("The quick brown fox jumped over the lazy dog"))

Sin embargo, una forma mucho más fácil de realizar esta tarea es dividir la cadena por un espacio, mapear las palabras y obtener la longitud de cada palabra, luego usar Math.max y extender la sintaxis para obtener el elemento más grande:

 function findLongestWordLength(str) { return Math.max(...str.split(" ").map(e => e.length)) } console.log(findLongestWordLength("The quick brown fox jumped over the lazy dog"));

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!