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

270
Views
¿Por qué el segundo código no funciona igual que el primero?

El primer código funciona correctamente y muestra la respuesta correcta, que es 19.

 function findLongestWordLength(str) { let high = 0; let word = str.split(" "); for(let i = 0; i < word.length; i++) { if (word[i].length > high) high = word[i].length; } console.log(high) } findLongestWordLength("What if we try a super-long word such as otorhinolaryngology");

El segundo código a continuación, solo funciona hasta la palabra "superlargo" y registra 10 como resultado final, lo cual es incorrecto. Estoy tratando de averiguar qué va mal aquí. Funciona bien con otras oraciones,

PARA REFERENCIA

La longitud de cadena en la oración es 60 (espacios incluidos), y hay 9 espacios entre la oración completa

 function findLongestWordLength(str) { let high = 0; let count = 0; for (let i = 0; i < str.length; i++) { if (str[i] != " ") { count++; } else { if (count >= high) high = count; count = 0; } } return high; } findLongestWordLength("What if we try a super-long word such as otorhinolaryngology");
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

count podría tener un valor distinto de cero al final del bucle, que se ignorará. Simplemente agregue una marca al final del ciclo también para actualizar ese valor.

 for(let i = 0; i < str.length; i++) { if (str[i] != " ") count++; else { if(count >= high) high = count; count = 0; } } if(count >= high) high = count;
about 4 years ago · Juan Pablo Isaza Report

0

Para obtener 19, debe terminar su cadena con un espacio. Debido a que el último carácter de "otorhinolaryngology" es una 'y' , simplemente incrementa el conteo al final y nunca alcanza su else condición, que se actualizará en un nivel alto. Ponga un espacio al final, agregue una condición extra verificando si i == str.length -1 O simplemente use el algoritmo de longitud, o, como prefiero, use un reductor así:

 const findLongestWordLength = str => str.split(' ').reduce((acc, word) => word.length > acc ? word.length : acc, 0)
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!