【问题标题】:How can I formulate the function solution? [closed]如何制定功能解决方案? [关闭]
【发布时间】:2020-06-01 11:39:55
【问题描述】:

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. 然后得到平方和(我不确定我是否写对了,哈哈)数字。谢谢!

【问题讨论】:

    标签: javascript arrays function


    【解决方案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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-11
        • 1970-01-01
        相关资源
        最近更新 更多