简体   繁体   English

将变量值推入数组

[英]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 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 Array.push返回已更改数组的长度,而不是数组本身

See the Docs 查看文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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