简体   繁体   English

返回返回未定义但控制台返回值

[英]Return returns undefined but console returns value

Algorithm for the recursive sum of all the digits in a number.一个数字中所有数字的递归和的算法。 Example: 942 --> 9 + 4 + 2 = 15 --> 1 + 5 = 6.示例:942 --> 9 + 4 + 2 = 15 --> 1 + 5 = 6。

Could someone tell me why there is a correct sum in the console when i print it by console.log but when i want to return there is undefined?有人能告诉我为什么当我通过console.log打印时控制台中有正确的总和但是当我想返回时没有定义?

let sum = 0;

const sumOfDigits = (num) => {
  let number = num.toString();

  if (number.length > 1) {
    sum = 0;
    [...number].forEach((digit) => {
      sum += Number(digit);
    });
    sumOfDigits(sum);
  } else {
    console.log(sum);
    return sum;
  }
};

console.log(sumOfDigits(942));

You dont return the value for all the calls您不会返回所有调用的值

Change sumOfDigits(sum);改变sumOfDigits(sum); to return sumOfDigits(sum); return sumOfDigits(sum); like below像下面

 let sum = 0; const sumOfDigits = (num) => { let number = num.toString(); if (number.length > 1) { sum = 0; [...number].forEach((digit) => { sum += Number(digit); }); return sumOfDigits(sum); } else { console.log(sum); return sum; } }; console.log(sumOfDigits(942));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM