javascript 对数组中的连续数字求和并跳过错误值JS

h22fl7wq  于 2022-12-10  发布在  Java
关注(0)|答案(4)|浏览(104)

我有一个包含这些值的数组

const arr = [NaN, NaN, 1, 2, 3, NaN, NaN, 4, 5, 6, 7, NaN, 8, 9, 10, NaN, 100, 200, 300, 400, 500];

如何对这些连续的值求和,同时跳过假值(NaN),并使用此假值作为子求和的分隔符。
预期结果:

const res = [6, 22, 27, 1500]

到目前为止,我尝试实现reduce(),但可能是错误的方式,而且常规的for循环也没有得到预期的结果。

ezykj2lf

ezykj2lf1#

如果数字之和为0,则需要执行isNaN测试。
建议代码:

const arr = [NaN, 1, -1, NaN, 1, 2, 3, NaN, NaN, 4, 5, 6, 7, NaN, 8, 9, 10, NaN, 100, 200, 300, 400, 500];
//                ^^^^^^ added those in the example
const sums = arr.reduce((acc, val, i) => {
    if (!Number.isNaN(val)) {
        if (Number.isFinite(arr[i-1])) val += acc.pop();
        acc.push(val);
    }
    return acc;
}, []);

console.log(sums);
9ceoxa92

9ceoxa922#

您可以使用条件跳过错误值来执行此操作:

const arr = [NaN, NaN, 1, 2, 3, NaN, NaN, 4, 5, 6, 7, NaN, 8, 9, 10, NaN, 100, 200, 300, 400, 500];
const countValid = (arr) => {
    let  total = 0;
    let   result = []
    for (let i = 0; i < arr.length; i++)
    {
        if (arr[i]) total+=arr[i]
        else if (total !== 0) {
            result.push(total);
            total = 0;
        }
    }
    if (total !== 0)
      result.push(total)
    return result;
}
console.log(countValid(arr)) // prints expected output [6, 22, 27, 1500]
zf9nrax1

zf9nrax13#

如果NaN和NaN之间的一系列数字之和为0(假设有负数),这也会起作用。

const arr = [NaN, NaN, 1, 2, 3, NaN, NaN, 4, 5, 6, 7, NaN, 8, 9, 10, NaN, 100, 200,NaN,1,-1,NaN, 300, 400, 500];

const result = []
let sum=0;
arr.forEach((num,i)=>{

  if(isNaN(num)) {
        if(!isNaN(arr[i-1])){
        result.push(sum)
        sum=0;
        return;
       }
   return;
 }
sum+=num;
if(i===arr.length-1) result.push(sum)
})

console.log(result)
klr1opcd

klr1opcd4#

您可以尝试以下代码:

let arr = [NaN, NaN, 1, 2, 3, NaN, NaN, 4, 5, 6, 7, NaN, 8, 9, 10, NaN, 100, 200, 300, 400, 500];
let sum = 0;

for (let i = 0; i < arr.length; i++) {
  if(arr[i]) sum += arr[i];
}

console.log(sum); // 1515

相关问题