7

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
 });
}
Peter Mortensen
31.3k22 gold badges110 silver badges134 bronze badges
asked Jul 20, 2016 at 17:43
2
  • 1
    it should be array of objects and can't see micronConv here. 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? Commented Jul 20, 2016 at 17:59

2 Answers 2

9
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;
answered Jul 20, 2016 at 17:45
Sign up to request clarification or add additional context in comments.

1 Comment

or even return my_arr.push(...) && my_arr; would work too ;-)
9

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

See the Docs

answered Jul 20, 2016 at 17:45

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.