简体   繁体   中英

Javascript .reduce()

I am doing freeCodeCamp JavaScript. I am on the question: Basic Algorithm Scripting: Factorialize a NumberPassed

Here is the code I have written:

function factorialize(num) {
  let arr = [];
  let reducer = (accumulator, currentValue) => accumulator * currentValue;
  for (let i = 1; i < num + 1; i++) {
    let newArr = arr.push(i);
  }
  return newArr.reduce(reducer);
}
factorialize(5);

Here is my problem: the console says this:

ReferenceError: newArr is not defined

Why is it saying that newArr is not defined? I DID define it! I am relatively new to coding and I really want to learn. Please help me.

  1. You don't need newArr at all.

  2. Array.prototype.push returns length of the array.

  3. You cannot get a variable declared with let in for statement and that caused an error.

 function factorialize(num) { let arr = []; let reducer = (accumulator, currentValue) => accumulator * currentValue; for (let i = 1; i < num + 1; i++) { arr.push(i); } return arr.reduce(reducer); } console.log(factorialize(5));

you can simply do that

 const factorialize=num=>Array(num).fill(1).reduce((a,_,i)=>a*++i) console.log('5! ->', factorialize(5) ) console.log('3! ->', factorialize(3) )

You can use recursion instead of reduce if you want to:

function factorialize(num) {
   while (num  > 1) {
     return num * factorialize(num - 1);
        }
    return num;
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM