Javascript平方数组中的所有元素不起作用 [英] Javascript square all element in array not working

查看:58
本文介绍了Javascript平方数组中的所有元素不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 函数square(arr){var result = [].concat(arr);result.forEach(function(i){i = i * i;console.log(i);})返回结果;}var arr = [1,2,3,4];console.log(square(arr)) 

任务是将数组中的所有元素平方,现在我的输出是原始数组.我想知道为什么.

P.s.第一个console.log给了我output1; 4; 9; 16.第二个console.log输出[1,2,3,4]

解决方案

forEach 正在迭代数组,但未返回任何值.请使用map函数,该函数将返回具有更新结果的新数组

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

如果您仍然打算使用 forEach 将更新后的值推送到数组中并返回该数组

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]

解决方案

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

这篇关于Javascript平方数组中的所有元素不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆