我是Javascript的新手,所以请允许我回答这个基本问题,

我正在尝试让我的函数将字符串中的所有单个数字加在一起,然后继续执行直到我剩下一个数字为止!

3253611569939992595156

113 // result of the above digits all added together

5 //result of 1+1+3


我创建了一个while循环,但它只将数字加在一起一次,直到一个数字都不会重复,我也不知道为什么!



function rootFunc(n) {
  var splite = n.toString().split('').map(x => Number(x)); //converts the number to a string, splits it and then converts the values back to a number

  while (splite.length > 1) {
    splite = splite.reduce(getSum);
  }

  return splite;
}

console.log(rootFunc(325361156993999259515));

function getSum(total, num) {
  return total + num;
}

最佳答案

您正在适当地减少,但您没有做的就是重新拆分。尝试将其分解为单独的功能:

function digits(n) {
  return n.toString().split('').map(x =>Number(x));
}


然后每次拆分:

function rootFunc(n) {
  var d = digits(n);
  while (d.length > 1) {
    d = digits(d.reduce(getSum));
  }

  return d;
}

10-07 21:42