1

I am trying to create an array and add data to the beginning of it. Then with a for loop I print out all the data. However, it prints an error, as Uncaught TypeError: Cannot read property 'title' of undefined.

var coords=new Array();

coords.unshift({tite:"sadsad asdds",artist:"Tik Taak"});
coords.unshift({title:"Heyyy sd",artist:"shahram"});
coords.unshift({title:"brahhh",artist:"Daniel"});


for(var i = 0; i <= coords.length; i++){
	console.log(coords[i].title + " - " + coords[i].artist);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

As you can see one of the items is printed as undefined. And I think thats the point the error is triggered.

Any idea how to solve it?

Thanks in advance

2 Answers 2

4

Omitting the fact, that you had a typo in your first object (title != tite) - change <= to < inside the for loop, else it will return undefined error, because it looks for the element on index 3, which actually doesn't exist.

var coords = new Array();

coords.unshift({title:"sadsad asdds",artist:"Tik Taak"});
coords.unshift({title:"Heyyy sd",artist:"shahram"});
coords.unshift({title:"brahhh",artist:"Daniel"});

for (var i = 0; i < coords.length; i++) {
  console.log(coords[i].title + " - " + coords[i].artist);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Sign up to request clarification or add additional context in comments.

Comments

4

Looks like your first array object, title is misspelled.

1 Comment

Also the for has to be i < coords.lengthotherwise it will go to index 3 and cause yet another error.

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.