Javascript Problem - Functions in loop?

I’m (attempting to) write a cross-platform web app which seems to be putting my skills to the test. I’m struggling with a function within a loop.

The flow like so:

User downloads app - assumed connected to internet - fetch data and store in local storage.

User loads app - if connected download data again and store again / else fall back on local data

Problem? I’m not overly experienced in JS and never really needed to use it for data manipulation. I basically want to limit the string length of the body of news stories.

From console:

[PHP]
"+ truncateTitle(data.stories[i].body) + "
[/PHP]

Code:
[PHP]

Test
[/PHP]

I can find lots of resources online, but none to do it within a loop. Please help! I’m going stir crazy on this one!

The error you got

Uncaught TypeError: Cannot read property 'length' of undefined

Probably what you got in the stack trace in the console

 "+ truncateTitle(data.stories[i].body) + "

This is not the error however, the error is in the truncateTitle function, try to log out title in that function and you will probably see that somewhere in the loop you get a story without a body (hence cannot read property length of undefined)

function truncateTitle (title) { console.log(title); var length = 25; if (title.length > length) { title = title.substring(0, length)+'...'; } return title; }

Cheers, I managed to get around it like you said, it wasn’t reading it as a string.

Sponsor our Newsletter | Privacy Policy | Terms of Service