我有一个包含这些值的数组
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循环也没有得到预期的结果。
我有一个包含这些值的数组
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循环也没有得到预期的结果。
4条答案
按热度按时间ezykj2lf1#
如果数字之和为0,则需要执行
isNaN
测试。建议代码:
9ceoxa922#
您可以使用条件跳过错误值来执行此操作:
zf9nrax13#
如果NaN和NaN之间的一系列数字之和为0(假设有负数),这也会起作用。
klr1opcd4#
您可以尝试以下代码: