最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Pushing a variable value into an array - Stack Overflow

programmeradmin5浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 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;

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

See the Docs

发布评论

评论列表(0)

  1. 暂无评论