Skip to content Skip to sidebar Skip to footer

Javascript Object Getting Undefined In Fixed-length For Loop

I have a JSON object that I parse using jQuery's parseJSON function. I assign one of the child objects to a local variable which I then iterate over using a for loop as follows: va

Solution 1:

Instead of

for (var i = 0; i < 10; i++) {

Add the check condition for the array object

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

Maybe the array you are referring to might not have 10 entries in it. The later approach should solve the problem..

Solution 2:

If you want to get the first ten posts, replace

for (var i = 0; i < 10; i++) {

with

for (var i = 0; i < 10 && i < posts.length; i++) {

Solution 3:

Use foreach instead of fixed-length for loop.

Post a Comment for "Javascript Object Getting Undefined In Fixed-length For Loop"