返回数字的总和(正数或负数) [英] Return sum of a number (positive or negative)

查看:99
本文介绍了返回数字的总和(正数或负数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要制作一个接受数字并返回数字总和的函数,如果数字为负数,则在添加数字时应将第一个数字视为负数,这就是我的意思:

I need to make a function that takes a number and returns sum of it's digits, if the number is negative the first digit should be considered negative when adding numbers, this is what I have:

var arrx = [];
var oper;
var others = 0;

function sumDigits(num) {
    // your code here
    var y = num.toString();
    var c = y.split("");
    c.forEach((h) => arrx.push(Number(h)) );
    if (num < 0){
        oper = -arrx[0];
        for (var z = 1; z < arrx.length; z++){
            others += arrx[z];
        }

        return others + oper;
    }

    return arrx.reduce((a,b) => a+b);
}

sumDigits(1234);

给定负数时,函数返回NaN,这是什么问题?

When given negative number, function returns NaN, what's the problem ?

推荐答案

使用优化的简短版本的 sumDigits()函数:

Use optimized and short version of sumDigits() function:

function sumDigits(num) {
  var isNeg = num < 0,   // check whether the number is negative
      numbers = (isNeg? String(num).slice(1) : String(num)).split('').map(Number);
  if (isNeg) numbers[0] *= -1;   // 'recovering' the number's sign

  return numbers.reduce(function(a,b){ return a + b; });
}

console.log(sumDigits(1234));
console.log(sumDigits(-951));

这篇关于返回数字的总和(正数或负数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆