I am currently working on a problem in coderbytes. I am supposed to create a function that takes in a string and returns the longest word in the string(no punctuation will be in the string and if there are two words the same size the function should return the first one). I was able to find a similar question Find the longest word/string in an array , but for some reason my code is not working.
var longestword = function(string){
var longest = [];
array = string.split(" ");
for(var i = 0; i <= array.length; i++){
if(array[i].length > longest.length){
longest = array[i];
}
}
console.log(longest)
}
longestword("This isnt workin for some reason")
The error I am getting is TypeError: array[i] is undefined
Your condition is i <= array.length
, but array indexes (for non-sparse arrays like this one) are 0
through array.length - 1
. Just use <
, not <=
. You're getting undefined
for array[i]
when i
is array.length
because there's no element there.
Unrelated, but: Your code is falling prey to The Horror of Implicit Globals because you never declare array
. Add a var
in front of array = string.split(" ");
You can't access array[array.length]. Arrays are 0-based. Change the <= to an <.
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.