简体   繁体   English

如果在 reduce() 中检查总和 function

[英]if checks inside a reduce() sum function

I am trying to iterate through an array in typescript, but on occasion, inside the array there will be an empty value or NaN (null) value by default.我正在尝试遍历 typescript 中的数组,但有时,默认情况下,数组内部会有一个空值或 NaN(空)值。 this really mucks up my sum function, as it is trying to call parseInt() on a null value, so the function also returns NaN.这真的搞砸了我的总和 function,因为它试图在 null 值上调用 parseInt(),所以 function 也返回 NaN。 How can I make an if condition inside of this function to check for Number() first otherwise skip/continue?我怎样才能在这个 function 中创建一个 if 条件来首先检查 Number() 否则跳过/继续? I know I can naively have a for each loop, and check for this inside of an if statement, but that is not ideal.我知道我可以天真地拥有一个 for each 循环,并在 if 语句中检查它,但这并不理想。

    sumOwnershipLiabilityPercentages(): number{
        // return the sum of all the percentage ownerships
        return this.liabilitiesOwnershipList.reduce((prev: number, cur: any) => prev + parseInt(cur.percentage), 0);
    }

You can make the summation conditional.您可以使求和有条件。

const sum = d.reduce((p: number, c: number) => p += (c) ? c : 0)

if you want to make a more elaborate if statements do it like so如果你想做一个更详细的 if 语句,就这样做

const sum2 = d.reduce((p: number, c: number) => {
   if (c)
      return p += c;
   else
      return p += 0;
   })

or, in your case, something like this或者,在你的情况下,是这样的

return this.liabilitiesOwnershipList.reduce((prev: number, cur: any) => {
    if (cur && cur?.percentage)
      return prev += parseInt(cur.percentage);
    else
      return prev += 0;
  });

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

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