Javascript square all element in array not working

前端 未结 3 1148
没有蜡笔的小新
没有蜡笔的小新 2021-01-29 13:36
function square(arr) {
   var result=[].concat(arr);
   result.forEach(function(i){
      i=i*i;
      console.log(i);
   })
   return result;
 }
var arr=[1,2,3,4];
cons         


        
3条回答
  •  [愿得一人]
    2021-01-29 13:56

    You could define a square function for a single value as callback for Array#map for getting a squared array.

    function square(v) {
        return v * v;
    }
    
    var array = [1, 2, 3, 4];
    
    console.log(array.map(square));

提交回复
热议问题