Simple function returning 'undefined' value

前端 未结 6 754
春和景丽
春和景丽 2020-12-28 19:28

This is the function I am currently working on:

function getSmallestDivisor(xVal) {    

    if (xVal % 2 === 0) {
        return 2;
    } else if (xVal % 3          


        
6条回答
  •  [愿得一人]
    2020-12-28 20:08

    I really can't resist to write this...because your question and all of the answers helped me so much. I had the exact same problem, I wrote recursive function and omitted return keyword. This page saved me hours of staring at the editor.

    The task:

    Digital root is the recursive sum of all the digits in a number. Given n, take the sum of the digits of n. If that value has more than one digit, continue reducing in this way until a single-digit number is produced.

    function digital_root(n) {
      if(n < 10) {
        return n;
      }
       let toString =  String(n);
       let splitted = toString.split('');
      
       let summArrayItems = function (arr) {
        let total = 0;
          for(let i = 0; i < arr.length; i++) {
            total += Number(arr[i]);
          }
          return total;
        }
      let output = summArrayItems(splitted);
      
      if(output < 10) {
       return output;
      } else {
        return digital_root(output); // In this line I omitted return keyword, and received undefined
      }
    }

提交回复
热议问题