简体   繁体   中英

Getting sum using += doesn't work in here. Why?

I'm trying to return true or false if given value is narcissistic number.

After assigned empty variable sum, then try to getting sum using +=

But, I don't know It doesn't work in here.

function narcissistic(n) {

  let arr =  Array.from(String(n), Number);
  // ex) 999 => [9,9,9]

  let sum;

  arr.forEach((e) => {
    sum += Math.pow(e,arr.length)   ;
  })

  return sum === n ? true: false

}

It results in NaN. Have no idea why? So I had to use this one and It works.

function narcissistic(n) {

  let arr =  Array.from(String(n), Number);
  // ex) 999 => [9,9,9]

  let newArr = [];

  arr.forEach((e) => {
     newArr.push(Math.pow(e,arr.length))   ;
  })

  let sum =  newArr.reduce((a,b) => a+b);

  return sum === n ? true: false

}

So my question is why the first one doesn't work when it comes to sum += ??

You need to make sum equal to 0 - it starts out life as undefined , and any mathematics with undefined leads to NaN .

let sum = 0;

This should fix your problem.

A more concise way to do this is with reduce :

let sum = arr.reduce((a, c) => a + Math.pow(c, arr.length));

We should initialize your variable before referencing.

let sum = 0;

It could solve your issue.

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