为了账号安全,请及时绑定邮箱和手机立即绑定

要求解释代码的某些部分

要求解释代码的某些部分

慕码人8056858 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) // --> 14let output2 = sumDigits(-316)console.log(output2) // --> 4但是当我在搜索的时候,我发现这段代码和reduce在一行中,有些代码我看不懂,这就是我问你们的原因。这是代码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我 的问题是为什么? 如果有人不介意解释其余代码,我们将不胜感激。 感谢提前。aarr[idx+1] *= -1
查看完整描述

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


查看完整回答
反对 回复 2023-01-06
?
阿晨1998

TA贡献2037条经验 获得超6个赞

我将重点关注 reduce 方法的部分。reduce Array 方法可以接收两个参数,第一个表示将“减少”数组的回调,这个回调可以接收 4 个参数:

  1. 电池

  2. 当前值

  3. 当前指数

  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)

我认为你可以贬低故事的其余部分。


查看完整回答
反对 回复 2023-01-06
?
长风秋雁

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


查看完整回答
反对 回复 2023-01-06
  • 3 回答
  • 0 关注
  • 124 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信