C. Kelly C. Kelly - 4 months ago 10
Javascript Question

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
});
}

Answer
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;