如何制定功能解决方案?

时间:2020-06-01 11:39:55

标签: javascript arrays function

x = [1, 2, 3, 4]
t = []
c = []
for(i = 0; i<x.length; i++){
   function solution(){
       t = Math.pow(x, 2)
       c = t[i]++
    return c
   } 
}

该功能需要:

  1. 计算数组编号的平方
  2. 然后得到平方和(我不确定我是否写对了,哈哈)。谢谢!

2 个答案:

答案 0 :(得分:1)

const result = [1, 2, 3, 4].map(n => n ** 2).reduce((acc, val) => acc + val, 0);

console.log(result);
您还可以使用比**更快的Math.pow()运算符。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators

答案 1 :(得分:0)

var result = [1, 2, 3, 4].map(n => Math.pow(n, 2)).reduce((acc, val) => acc + val, 0);

console.log(result);