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
});
}
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
});
}
Share
Improve this question
edited Jul 20, 2016 at 19:26
Peter Mortensen
31.6k22 gold badges110 silver badges133 bronze badges
asked Jul 20, 2016 at 17:43
C. KellyC. Kelly
2173 silver badges10 bronze badges
2
-
1
it should be array of objects and can't see
micronConv
here. – Varit J Patel Commented Jul 20, 2016 at 17:44 -
2
Why so many upvotes? That code doesn't return an array. And did you check
my_arr
? – 1983 Commented Jul 20, 2016 at 17:59
2 Answers
Reset to default 9return 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;
Array.push
returns a length of the changed array, not the array itself
See the Docs