Javascript square all element in array not working

前端 未结 3 1175
没有蜡笔的小新
没有蜡笔的小新 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:59

    forEach is iterating the array but it is not returning anyvvalue.Use map function which will return a new array with updated result

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

    If you still intend to use forEach push the updated values in an array and return that array

提交回复
热议问题