error: Uncaught TypeError: n.split is not a function

function digital_root(n) {
  n.toString()
  let x = n.split('')
  while (x.length != 1) {
    let root = 0
    x.forEach(function(digit) {
      root += Number.parseInt(digit, 10)
    })
    x = root
  }
  return x
}
console.log(digital_root(22))

При сплите выводит ошибку error: Uncaught TypeError: n.split is not a function n - целочисленное, программа складывает цифры в числе пока число не станет одной цифрой


Ответы (2 шт):

Автор решения: ReinRaus

n.toString() не изменяет объект n, а возвращает результат приведения типа.
Вы этот результат никак не используете. Должно быть так:

n = n.toString();

Либо, применительно к Вашему коду:

let x = n.toString().split( '' );

P.S. При написании кода на JavaScript рекомендуется явно использовать ; в конце команды.

→ Ссылка
Автор решения: Igor

function digital_root(n) {
  let x = n.toString().split('');
  while (x.length > 1) {
    x = (n = x.reduce((r, d) => r += +d, 0)).toString().split('');
  }
  return n;
}

console.log(digital_root(22));
console.log(digital_root(999));
console.log(digital_root(9991));

→ Ссылка