The script should add the numbers from which the number consists and display the result. But returns NaN. Why?

digital_root(16); function digital_root(n) { var result; n = n.toString(); for (var i = 0; i<n.length; i++) { n[i] = Number(n[i]); result += n[i]; result = Number(result); } console.log(result); } 
  • n.length - the number does not have the length property - Igor
  • 1) Primitives have no properties. The number is primitive. 2) Do not use wrappers like Number . 3) Logic and console says that there is no return, and only undefined can be. - user207618 5:26 pm
  • Updated. Used n = n.toString () to convert to a string to find out the length. - Sergey Alekseev
  • it got worse. n[i] = Number(n[i]); - what does that do now? - Igor
  • @SergeyAlekseev, primitives have no properties. - user207618

1 answer 1

The problem is that the lines in javascript are immutable, so you can not do so

 n[i] = Number(n[i]); 

Instead, it was necessary to assign the value of a new variable:

 digital_root(16); function digital_root(n) { var result = 0, nStr = n.toString(); for (var i = 0; i < nStr.length; i++) { result += Number(nStr[i]); } console.log(result); } 

  • Raise to fn = n => (n + '').split``.reduce((a, n) => a += +n, 0); . - user207618
  • @Other, fn=(n,i=0,r=0)=>{n+='';for(;n[i];i++)r+=+n[i];return r} - Grundy
  • However, monsieur, however ... Only I still have a shorter solution. - user207618
  • @Other, my current character is two characters shorter - Grundy
  • Spaces will be removed and will be less than 11 characters: fn=n=>(n+'').split``.reduce((a,n)=>a+=+n,0); . - user207618