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!!!
push() The push() method adds one or more elements to the end of an array and returns the new length of the array.
The arr. push() method is used to push one or more values into the array. This method changes the length of the array by the number of elements added to the array. Parameters This method contains as many numbers of parameters as the number of elements to be inserted into the array.
Prevent adding Duplicates to an Array using indexOf #Use the indexOf() method to check that the value is not present in the array. The indexOf method returns -1 if the value is not contained in the array. If the condition is met, push the value to the array.
Method push() returns the last element added, which makes it very inconvenient when creating short functions/reducers.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With