gpt4 book ai didi

javascript - 在数组内部使用 parseFloat

转载 作者:行者123 更新时间:2023-11-28 11:21:01 25 4
gpt4 key购买 nike

当数据位于数组内部时,如何使用 parseFloat?

假设我收到这样的 api 响应:

$scope.response = [{name: "Richard", qty: "350.99"},
{name: "Chuck", qty: "199"},
{name: "Phonenix", qty: "233.77"}]

我想对 qty 的值求和,但我不能因为数据类型而改变。如果我需要在 qty 上使用 parseFloat,我怎样才能只获取这些值?

我必须使用诸如 some() 之类的东西来获取 qty 值?

我正在使用 AngularJs 和 Javascript。

最佳答案

您可以迭代数组并使用 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);

关于javascript - 在数组内部使用 parseFloat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48193258/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com