简体   繁体   中英

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

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

See the Docs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM