Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pushing a variable value into an array

Problem

I am trying to push a returning variables value into an array. This is my code, however I'm returning an empty array and am not sure what's wrong.

JavaScript

var my_arr = [];

function foo() {
  var unitValue = parseFloat($('#unitVal1').val());
  var percentFiner = parseFloat($('#percent1').val());
  var total = unitValue * 1000;

  return my_arr.push({
    unit: unitValue,
    percent: percentFiner
  });
}
like image 364
C. Kelly Avatar asked Jul 20 '16 17:07

C. Kelly


2 Answers

return my_arr.push({
        unit:   unitValue, 
        percent: percentFiner});

This isn't returning the new Array - this is returning the new length of the Array! Split these out:

my_arr.push({
        unit:   unitValue, 
        percent: percentFiner});

return my_arr;
like image 117
tymeJV Avatar answered Oct 20 '22 18:10

tymeJV


Array.push returns a length of the changed array, not the array itself

See the Docs

like image 26
Naftali Avatar answered Oct 20 '22 17:10

Naftali