Javascript push returning number instead of object

I'm sure this is just a simple stupid mistake that I am missing, but can someone tell me why it 3comes back instead [{ "method": 'popup', "minutes": ''}, {"method": 'email', "minutes": '10'}, {"method": 'popup', "minutes": '20'}];?

I did jsfiddle so you can see: 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;
}

Thank!!!

+4
source share
1 answer

Array#pushthe method works in situ, you do not need to assign it to a new variable. It will not return a new array, but will change the original one and return it length. That is why you get 3the result.

To get the desired result, just call it without assigning any variable:

reminders.push(newReminder);
+6
source

Source: https://habr.com/ru/post/1676303/


All Articles