James
James

Reputation: 6008

Minor JavaScript array error

var add = [];

add[0].url = data.url;
add[0].photo = data.thumb;

console.log(add);

This'll be an instant know for most JS people. The code above is failing, anyone able to tell me where I'm going wrong

Upvotes: 1

Views: 67

Answers (3)

John Hartsock
John Hartsock

Reputation: 86902

A different option for you; instead of pushing into an empty array, and declaring an empty object

var add = new Array(); //create new array object
add[0] = {url:data.url, photo:data.thumb}; //add new object with items url and photo

Upvotes: 3

John Kugelman
John Kugelman

Reputation: 362187

You are assigning to properties of the add[0] object but you haven't made any such object.

add[0] = { };
add[0].url = data.url;
add[0].photo = data.thumb;

Upvotes: 4

meder omuraliev
meder omuraliev

Reputation: 186762

add[0] doesn't exist... .push something first.

add.push({ url:data.url, photo:data.thumb })

or

add[0] = {};
add[0].url = 'blah';
add[0].photo = 'foo'

Upvotes: 6

Related Questions