数字总和为 JavaScript 中数字的多位数字
我们需要编写一个JavaScript函数,它接受两个数字,比如m和n作为参数。
n将始终小于或等于m中的位数。该函数应计算并返回m的前n位数字之和。
例如-
如果输入数字是-
const m = 5465767; const n = 4;
那么输出应该是-
const output = 20;
因为5+4+6+5=20
示例
以下是代码-
const m = 5465767;
const n = 4;
const digitSumUpto = (m, n) => {
if(n > String(m).length){
return 0;
};
let sum = 0;
for(let i = 0; i < n; i++){
const el = +String(m)[i];
sum += el;
};
return sum;
};
console.log(digitSumUpto(m, n));输出结果以下是控制台输出-
20