Home > Blockchain >  JavaScript: rest operator function returning NaN
JavaScript: rest operator function returning NaN

Time:10-23

I'm trying to resolve some FCC tuts. The function should be very simple, a sum function for args as an array, using the rest operator. However I don't get why my answer doesn't work, here is the code with some parameters:

function sum(...args) {
  if (args == []) {
    return 0
  } else {
    let sum = 0;
    for (let i of args) {
      sum = sum   args[i];
      i  ;
    }
    return sum;
  };
};

// Using 0, 1, 2 as inputs, 3 is expected to return... and it does!
sum(0, 1, 2);

// However, if the args do not start with 0, it returns NaN
sum(1, 2);

CodePudding user response:

Change this:

    for (let i of args) {
      sum = sum   args[i];

To this:

    for (let i of args) {
      sum = sum   i;

Or to this:

    for (let i = 0; i < args.length; i  ) {
      sum = sum   args[i];

CodePudding user response:

I came up with a solution for your problem.

for(let i of args){
  // i is = the value ex: 12
  sum  = i;
}

But instead of that code you can use a more simplified one like this.

function sum(...nums) {
  return nums.reduce((total, num) => {
    return (total  = num);
  }, 0);
}

  • Related