Square each number in an array in javascript

后端 未结 14 1099
悲&欢浪女
悲&欢浪女 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 09:07

    function map(square,a) {
      var result = [];
      for(var i=0;i<=a.length-1;i++)
       result[i]=square(a[i]);
      return result;
    }
    
    var square = function(x) {
       return x*x;
    }
    
    var value=[1,2,3,4];
    var final= map(square,value);
    console.log(final);
    

    You can also try the above code snippet.

提交回复
热议问题