iT邦幫忙

0

codewars-Square(n) Sum 出現問題

附上相關連結
https://www.codewars.com/kata/515e271a311df0350d00000f/train/javascript

function squareSum(num){
  let newNum = num.map(x =>  x*x);
  console.log(newNum);
  if(newNum.length>0){
    return newNum.reduce((prev,curr)=>prev+curr);
  }
}

顯示結果為
Basic Tests
Should pass sample tests
Log
[ 1, 4 ]
[ 1, 4 ]
[ 0, 9, 16, 25 ]
[]
expected undefined to equal 0
我不知道如何處理這個問題,以及為什麼,有人可以幫助我一下嗎?

咖咖拉 iT邦研究生 1 級 ‧ 2021-10-20 17:25:32 檢舉
```
Time: 738msPassed: 1Failed: 0
Test Results:
Tests
test
Completed in 4ms
You have passed all of the tests! :)
```

1 個回答

2
海綿寶寶
iT邦大神 1 級 ‧ 2021-10-20 17:40:49
function squareSum(numbers){
  let newNum = numbers.map(x =>  x*x);
  if (newNum.length > 0) {
    return newNum.reduce((prev,curr)=>prev+curr);
  } else {
    return 0;
  }
}
淺水員 iT邦高手 2 級 ‧ 2021-10-20 18:15:29 檢舉
function squareSum(newNum) {
    return newNum.length > 0 ? newNum.reduce((prev, curr) => prev + curr * curr, 0) : 0;
}

想說都用 reduce 了,那個 map 就跳過了

我要發表回答

立即登入回答