Give a non-negative integer num, repeatedly adds the numbers in all positions until you get an one-digit integer.

<script>
    function getOne(num){
        var strArr=String(num).split("");
        var sum=strArr.reduce(function(init,item){
            init=init+Number(item);
            return init;
        },0);
        if(sum<10){
            return sum;
        }else{
            getOne(sum);
        }
    }
    console.log(getOne(343));
</script>

I would like to ask why the final printed result is undefined

Sep.06,2021

A return is missing

     function getOne(num){
        var strArr=String(num).split('');
        var sum=strArr.reduce(function(init,item){
            init=init+Number(item);
            return init;
        },0);
        if(sum<10){
            return sum;
        }else{
            return getOne(sum); // return
        }
    }
    console.log(getOne(343));

Why do you need to add return here?


suggest shorthand

function getOne(num){ 
  var strArr=String(num).split(''); 
  var sum = strArr.reduce(function(init,item){ 
    return init+Number(item); 
  },0);
  return sum<10? sum : getOne(sum);
}
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b3e6bf-2c406.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b3e6bf-2c406.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?