0

I am trying to work with data sent from a server using the following code where msg is the incoming data that holds two arrays:

console.log(msg);
for (var i = 0; i <= msg.cues.length; i++) {
  $("#cues").append("<div class=\"cue-item\" cueval=\"cue-" + i + "\"><h4>"+msg.cues[i].name+"</h4>"+msg.cues[i].description+"</div>");
}

This code adds the required elements to the page and everything seems to be fine from the browser window, but in the console I get the below error that blocks all other code from running:

{…}
  channels: Array [ 0, 0, 0, … ]
  cues: […]
    0: Object { name: "Cue 1", description: "This is a test cue" }

TypeError: msg.cues[i] is undefined

Any idea why this is happening and how I can solve this issue?

1
  • 1
    The for statement is wrong, it should be for (var i = 0; i < msg.cues.length; i++) Commented Dec 18, 2017 at 2:40

2 Answers 2

3

You're iterating one position past the length of the array. Change

for (var i = 0; i <= msg.cues.length; i++)

to

for (var i = 0; i < msg.cues.length; i++)
Sign up to request clarification or add additional context in comments.

Comments

1

Replace <= to < in for-loop head

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.