Joris Opsommer Joris Opsommer - 1 year ago 87
Javascript Question

Log words that start with a letter query with js

Trying to log all the words that start with a "b".
I am receiving the following error:
Uncaught TypeError: query[i].charAt is not a function.
Not sure what I'm doing wrong.

var query= [34,"beer","bbq","bees","aa","cc", "bb"];

for(var i=0;i<=query.length;i++){

Answer Source

The problem is that the first element in your array is a number. charAt is only defined for strings. Try this

var query= ["34","beer","bbq","bees","aa","cc", "bb"];

Alternatively, you can change query[i].charAt(0)=="b" to (query[i]+"").charAt(0)=="b". This will for each element of the array, convert it to a string so that then you can call charAt on it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download