3 回答

TA贡献1825条经验 获得超4个赞
您可以Math.abs在拆分之前使用数字并将其转换为字符串,然后使用 reduce 来计算总和。在从函数返回之前检查输入是小于还是大于 0 并相应地采取措施
function sumDigits(num) {
// toString will convert to string so an array of string can be created
const sum = Math.abs(num).toString().split('').reduce((acc, curr) => {
// converting string to number before adding with previous digit
// else it will do string concatenation instead of mathematical addition
acc += +curr;
return acc
}, 0);
return num < 0 ? -1 * sum : sum;
}
let output = sumDigits(1148);
console.log(output); // --> 14
let outpu2t = sumDigits(-316);
console.log(outpu2t); // --> -10

TA贡献2037条经验 获得超6个赞
我将重点关注 reduce 方法的部分。reduce Array 方法可以接收两个参数,第一个表示将“减少”数组的回调,这个回调可以接收 4 个参数:
电池
当前值
当前指数
大批
reduce 方法的第二个参数指示哪个值将启动回调的Acumulator参数。
一旦解释说,在您看到的示例中,他表示累加器将从 0 值开始:
.reduce(<...>, 0)
然后,在 reduce 方法的第一次迭代中,当前值的第一个值将是数组的 0 索引值。
num
如果我们考虑是的情况-316
,那么:
第一次迭代:回调变量将是:
a = 0
v = '-'
idx = 0
arr = ['-', '3', '1', '6']
该过程将是:
v === '-' //true, then:
v = 0
arr[idx+1] *= -1 //here, he are converting the value next to the sign to a negative value
a + +v //then, he add the v value to the acumulator with the corresponding sign.
第二次迭代:回调变量
a = 0
v = -3
idx = 1
arr = ['-', -3, '1', '6']
过程:
v === '-' //false, then:
a + +v //a = 0, v = -3. 0 + +(-3) = -3 (Number)
我认为你可以贬低故事的其余部分。

TA贡献1757条经验 获得超7个赞
简短回答:arr[idx+1] *= -1直接将数组中的下一个成员操作为负整数。
您可以在 Javascript Playground 上尝试以下代码,以查看每个循环步骤的变量值,以便更好地理解:(这是您试图理解的代码的扩展版本)
function sum(num) {
s = String(num)
.split('')
.reduce(function (a, v, idx, arr) {
console.log('a=', a, 'v=', v, 'idx=', idx, 'arr=', arr);
if (v === '-') {
v = 0;
arr[idx + 1] *= -1;
a += +v;
} else {
a += +v;
}
return a;
}, 0);
return s;
}
console.log(sum(1148));
console.log(sum(-316));
添加回答
举报