Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript push returning number instead of object [duplicate]

Tags:

javascript

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!!!

like image 608
Rbar Avatar asked May 03 '17 20:05

Rbar


People also ask

Does Push return a value?

push() The push() method adds one or more elements to the end of an array and returns the new length of the array.

How do you push a number in JavaScript?

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.

How do you push an object to an array without duplicates?

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.

Does Push return anything JavaScript?

Method push() returns the last element added, which makes it very inconvenient when creating short functions/reducers.


1 Answers

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);
like image 200
kind user Avatar answered Oct 22 '22 11:10

kind user