Square each number in an array in javascript

后端 未结 14 1026
悲&欢浪女
悲&欢浪女 2020-12-16 08:36

I\'m trying to square each number in an array and my original code didn\'t work. I looked up another way to do it, but I\'d like to know WHY the original code didn\'t work.<

相关标签:
14条回答
  • 2020-12-16 08:49

    Use embedded for , for pretty syntax :

          var arr=[1,2,3,4] ;
          [for (i of arr) i*i ]; 
    
          //OUT : > [1,4,9,16]
    
    0 讨论(0)
  • 2020-12-16 08:49

    Declarative Programming :)

    let list = [1,2,3,4,5,6,7,8,9,10];
    let result = list.map(x => x*x);
    console.log(result);

    0 讨论(0)
  • 2020-12-16 08:53

    How about that ?

    function (arr) {
      return arr.map(function (x) {
        return Math.pow(x, 2);
      });
    }
    

    Array.map(func) applies the function to each element of the map and returns the array composed of the new values. Math.pow(base, exp) raises base to its exp power.

    0 讨论(0)
  • 2020-12-16 08:56

    Here is the function write with ES6 Exponentiation (**):

    let arr = [1, 6, 7, 9];
    let result = arr.map(x => x ** 2);
    console.log(result);

    0 讨论(0)
  • 2020-12-16 08:56
    let arr = [1, 2, 3];
    let mapped = arr.map(x => Math.pow(x, 2));
    console.log(mapped);
    
    0 讨论(0)
  • 2020-12-16 09:01

    This will work

    const marr = [1,2,3,4,5,6,7,8,9,10]; console.log(marr.map((x) => Math.pow(x, 2)));

    0 讨论(0)
提交回复
热议问题