gpt4 book ai didi

javascript - 数组和某些数组空白的数组总和

转载 作者:行者123 更新时间:2023-12-02 21:54:29 25 4
gpt4 key购买 nike

这是数组

Product Details = [{Amount: '49.95'}, {Amount: ''}]

这里使用了 Javascript:

function() {
var prods = {{Product Details}}; // Product Araay
var Amount = 0;
var i, len;
for (i = 0, len = prods.length; i < len; i++) {
Amount += parseInt(prods[i].Amount);
}
return Amount;
}

============结果==============

NaN

最佳答案

  • 如果其值为 falsy 值,则将其默认为 0
  • 还可以使用 parseFloat 而不是 parseInt,因为您有 float 值:)

var Details = [{Amount: '49.95'}, {Amount: ''}, {Amount: '15.25'}]

function sums () {
var prods = Details; // Product Array
var Amount = 0;
var i, len;
for (i = 0, len = prods.length; i < len; i++) {
Amount += parseFloat(prods[i].Amount || 0);
}
return Amount;
}

console.log(sums())

关于javascript - 数组和某些数组空白的数组总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60044850/

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