javascript - Can someone explain how the routine below is logging "undefined" in console?
问题描述
Code snippet below suppose to log sum of digits in the given number.But, it returns undefined. Can someone please explain how it works under the hood?
const checkNumbers = (membershipId) => {
if (membershipId.length === 1) {
return membershipId;
}
if (membershipId.length > 1) {
sumOfNumbers = [...membershipId].reduce((a, b) => +a + +b, 0);
checkNumbers(sumOfNumbers.toString());
}
};
console.log(checkNumbers("555"));
解决方案
Because except for the length === 1 case, you don't have a return statement. If there's no return statement, then undefined
is returned implicitly once the end of the function is reached.
To fix it, change this:
checkNumbers(sumOfNumbers.toString());
To this:
return checkNumbers(sumOfNumbers.toString());
Full code:
const checkNumbers = (membershipId) => {
if (membershipId.length === 1) {
return membershipId;
}
if (membershipId.length > 1) {
sumOfNumbers = [...membershipId].reduce((a, b) => +a + +b, 0);
return checkNumbers(sumOfNumbers.toString());
}
};
console.log(checkNumbers('555'));
推荐阅读
- sql - 使用两种不同的条件获取 sum / count 的结果
- python - 为什么两种情况下的输出不同?
- office-js - 在 Excel Addin JS Addin 中使用本机 Excel 图标
- c++ - noexcept 运算符编译时检查
- c# - 动态添加对程序集的引用到 MSBuild
- javascript - 使用 pdf.js 在画布内的 pdf 上绘制一个矩形
- java - 如何在 onDataChange 中填充 ArrayList,arraylist 用于更新适配器
- javascript - 在 JavaScript 中订阅地图数据结构不起作用
- sql-server - 将 nvarchar 数据类型转换为 datetime 数据类型会创建超出范围的值
- r - 如何从本地文件夹目录正确安装软件包?