streetlight
streetlight

Reputation: 5968

Issue with .push()

I'm trying to do something really simple, but I think I'm making a stupid mistake.

I have an array full of objects, and I have a new object I want to put into that array. My code looks like this:

 var data = [ { id: 'S1', url: '1.html' } ];

 var newData = { id: '3', url: '3.html' };

console.log(data.push(newData))

For some reason, this keeps printing "2".

Here is a fiddle

Can anyone tell me what stupid mistake I'm making?

Upvotes: 1

Views: 132

Answers (2)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123453

You're using .push() correctly. But, are apparently expecting a different return value:

Returns

The new length property of the object upon which the method was called.

If you're trying to log the Array itself, you'll want to do that separately:

data.push(newData);
console.log(data);

As for the fiddle, you can use JSON.stringify() to serialize the Objects.

data.push(newData);
$('#here').text(JSON.stringify(data, null, 2))
[ { "id": "S1", "url": "1.html" }, { "id": "3", "url": "3.html" } ]

Simply using .text(data) will use each Object's toString(), which will simply result in:

[object Object],[object Object]

Upvotes: 4

Andbdrew
Andbdrew

Reputation: 11895

Array.protoype.push mutates the array it is called on and returns the new length of the array.

Check out the docs here!

Upvotes: 1

Related Questions