javascript push returning number instead of object [duplicate]
I'm sure this is just some simple silly mistake that I'm missing, but can anyone tell me why 3
is being returned instead of [{ "method": 'popup', "minutes": ''}, {"method": 'email', "minutes": '10'}, {"method": 'popup', "minutes": '20'}];
?
I made a jsfiddle so you can see as well: https://jsfiddle.net/qk10arb0/3/
HTML
<p>Click the button to add a new element to the array.</p>
<button onclick="addNewReminder()">Try it</button>
<p id="demo"></p>
Javascript
function addNewReminder(){
var newReminder = {
"method": 'popup',
"minutes": '20'
};
var reminders = [{
"method": 'popup',
"minutes": ''
}, {
"method": 'email',
"minutes": '10'
}];
reminders = reminders.push(newReminder);
document.getElementById("demo").innerHTML = reminders;
}
Thanks!!!
Solution 1:
Array#push
method works in situ, you don't have to assign it to a new variable. It won't return a new array, but will modify the original one and will return it's length
. That's why you are getting 3
as the result.
To get the desired result, just call it, without assigning to any variable:
reminders.push(newReminder);