Click here to Skip to main content
14,699,759 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to create an array called lengths which will have all the lengths of the elements in the array new_str.
The problem is when I am trying to push each length to the lengths array it says
‘Cannot read property ‘length’ of undefined’.
PS : My plan is to use Math.max() inorder to find the maximum length of the string in the array.


What I have tried:

function findLongestWordLength(str) {
var new_str = str.trim().split(" ");
var lengths = [];
for(var i=0; i <= new_str.length; i++){
lengths.push(new_str[i].length);
}
console.log(lengths);
}

findLongestWordLength("The quick brown fox jumped over the lazy dog");
Posted
Updated 13-Jul-20 3:33am

Two things:
1) The problem you have noticed is due to your loop:
for(var i=0; i <= new_str.length; i++){
Indexes run from 0 to N - 1, where N is the number of element in the array. You are trying to access 0 to N inclusive, so one of them does not have a value and you get an error.

2) Why do it like that? Just have a MaxValue integer, preset it to the first index value, and compare it to the current length each time round the loop. Why waste time and memory building a array you only use once?
   
It is failing because your loop is going beyond the end of the array. Array indices go from zero to the length of the array - 1. So you need to change your for loop test expression as follows:
for(var i=0; i < new_str.length; i++){ 
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900