Javascript square all element in array not working

房东的猫 提交于 2021-01-20 13:55:40

问题


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];
console.log(square(arr))

The task is to square all elements in an array, now my output is the original array. I wonder why.

P.s. the first console.log gives me the output1;4;9;16. the second console.log outputs [1,2,3,4]


回答1:


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




回答2:


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));



回答3:


  • Re-assigning that value to i won't update the original array.

  • You don't need to concat that array, just initialize that array as empty [].

  • Add every square value to the new array.

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


来源:https://stackoverflow.com/questions/49413342/javascript-square-all-element-in-array-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!