Reputation: 71
Beginner here. I was doing this exercise from Coding Addict.
The exercise:
function longestWords(str){
let words = str.split(" ");
let size = 0;
let max = [''];
for(let i=0; i<words.length; i++){
if(words[i].length >= size){
size = words[i].length;
if(max[max.length-1].length <words[i].length){
max = [];
max.push(words[i]);
}
else{
max = [...max,words[i]];
}
}
}
return [...max];
}
console.log(longestWords("I woke up early today"));
console.log(longestWords("I went straight to the beach"));
Now, When I tried changing the index for max[]
array to i
.
if(max[i].length <words[i].length){
I got this error:
Uncaught TypeError: Cannot read property 'length' of undefined at longestWords
Can someone tell me why I can't change the index and have to use max.length-1
instead?
Upvotes: 1
Views: 99
Reputation: 29
because your max array has always one element so there is no entry in the index 1 which is max[max.length], so you better actually write it as max[0]
instead.
Upvotes: 0
Reputation: 1003
When you use i, it represents the individual word in str. For example, "I woke up early today" has 5 words( or length = 5 ), but your max array has only 1 in length (which is ''). So if you use i to access max array you will get index out of bound. Unless you use the str has the same length as max.
Upvotes: 1