在数组中使用parseFloat

时间:2018-01-10 17:45:50

标签: javascript angularjs

当数据存在于数组中时,如何使用parseFloat?

让我说我得到这样的api回复:

{{ form.paragraph_data.initial|safe }}

我想总结$scope.response = [{name: "Richard", qty: "350.99"}, {name: "Chuck", qty: "199"}, {name: "Phonenix", qty: "233.77"}] 的值,但我不能'导致数据类型。如果我需要在qty上使用parseFloat,我怎样才能获得这些值?

我必须使用类似qty的内容来获取some()值?

我正在使用AngularJs和Javascript。

4 个答案:

答案 0 :(得分:3)

您可以迭代数组并使用Array.reduce

计算总和



const arr = [{
    name: "Richard",
    qty: "350.99"
  },
  {
    name: "Chuck",
    qty: "199"
  },
  {
    name: "Phonenix",
    qty: "233.77"
  }
];

const result = arr.reduce((sum, current) => {
  return sum + parseFloat(current.qty);
}, 0);

console.log(result);




答案 1 :(得分:2)

使用array#reduceqty数组的所有response求和。

var response = [{name: "Richard", qty: "350.99"},{name: "Chuck", qty: "199"},{name: "Phonenix", qty: "233.77"}],
    result = response.reduce((sum, {qty}) => sum += +qty, 0);

console.log(result);

答案 2 :(得分:2)

您可以映射数组以返回数量的parseFloat,然后使用reduce来添加值。

var response = [{
    name: "Richard",
    qty: "350.99"
  },
  {
    name: "Chuck",
    qty: "199"
  },
  {
    name: "Phonenix",
    qty: "233.77"
  }];

var sum = response.map(function(obj) {
    return parseFloat(obj.qty);
  })
  .reduce(function(a, b) {
    return a + b;
  }, 0);
  
console.log(sum)

答案 3 :(得分:2)

您可以使用reduce:

const response = [
  {name: "Richard", qty: "350.99"},
  {name: "Chuck", qty: "199"},
  {name: "Phonenix", qty: "233.77"}
];

const sumQuantities =
  response.reduce((acc, x) =>
    acc + parseFloat(x.qty)
  , 0);
    
console.log(sumQuantities);