要求解释代码的某些部分

2023-01-06 16:20:47

let output = sumDigits(1148);

console.log(output); // --> 14

let output = sumDigits(-316);

console.log(output); // --> 4

const sumDigits = num => {

let ar = num.toString().split('')  //Stringify the num and convert it to an array

let minSum = 0 // initialize the minSum counter and set to the value of 0

let plsSum = 0 // initialize the plsSum counter and set to the value of 0

//checking if the array start with '-', and if it's i'm going to remove it.

if (ar[0] === '-') {

ar.splice(0, 1)

ar.reduce((a, b) => minSum = Math.abs(a - b)) // subtracting the arrray of numbers and convet it to number after removing the first char.

}

// iterate over the array.

for (let i = 0; i < ar.length; i++) {

// adding the sum of array numbers to the initial var and convert it to a number

plsSum += Number(ar[i])

}

//returning the minSum and plsSum

if (minSum) {

return minSum

} else {

return plsSum

}

}

let output = sumDigits(1148)

console.log(output) // --> 14

let output2 = sumDigits(-316)

console.log(output2) // --> 4

`const sumDigits = num =>String(num).split('').reduce((a,v,idx,arr)=> v === '-' ? (v = 0, arr[idx+1] *= -1, a + +v) :a+ +v,0)`

`String(num).split('')` 在这部分中，他们将其串起来并将其转换为数组。✔

`reduce((a,v,idx,arr)` 在这部分中，他们用 4 个参数初始化 reduce。✔

`v === '-' ?`在这部分，他们检查是否`v`等于`'-'`，但问题是 在第一个输出 (1148)`v`中从1 开始，在第二个输出 (-316)中从 3 开始，因为将以1' -'对吧？然后他们设置(v = 0)。然后它们乘以-1 的问题是为什么？ 如果有人不介意解释其余代码，我们将不胜感激。 感谢提前。`a``arr[idx+1] *= -1`

3 回答

TA贡献1590条经验 获得超4个赞

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

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贡献1805条经验 获得超6个赞

1. 电池

2. 当前值

3. 当前指数

4. 大批

reduce 方法的第二个参数指示哪个值将启动回调的Acumulator参数。

`.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贡献1546条经验 获得超7个赞

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));

• 3 回答
• 0 关注
• 22 浏览

0/150