Pushing a variable value into an array

Problem

I am trying to print the return value of variables into an array. This is my code, however I am returning an empty array and do not know what happened.

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 }); } 
+7
javascript arrays
source share
2 answers
 return my_arr.push({ unit: unitValue, percent: percentFiner}); 

This does not return a new array - it returns the new length of the array! Separate them:

 my_arr.push({ unit: unitValue, percent: percentFiner}); return my_arr; 
+9
source share

Array.push returns the length of the modified array, not the array itself

See Documents

+9
source share

All Articles