map()和forEach()[复制]的特殊性

问题描述 投票:-2回答:1

这个问题在这里已有答案:

JavaScript中map()vs forEach的特殊性(特异性)是什么?

他们工作得很好!

 <script type="text/javascript"> "use strict";
   const array1 = [12, 3, 7];
   const array2 = [];

   const dispEls=(el, idx, array1) =>
       array2.push("exp (a[" + idx+ "] = "+el+") = "+
       Math.exp(el).toFixed(2));

   array2.push("===== FOREACH");
   array1.forEach(dispEls);
   array2.push("===== MAP");
   array1.map(dispEls);

   console.dir(array2)
 /*[…]
 0: "===== FOREACH"
 1: "exp (a[0] = 12) = 162754.79"
 2: "exp (a[1] = 3) = 20.09"
 3: "exp (a[2] = 7) = 1096.63"
 4: "===== MAP"
 5: "exp (a[0] = 12) = 162754.79"
 6: "exp (a[1] = 3) = 20.09"
 7: "exp (a[2] = 7) = 1096.63"
 length: 8      */
 </script>
javascript dictionary foreach
1个回答
3
投票

map返回一个数组,其中包含函数返回的值,而forEach则没有。如果您不需要新阵列,请选择forEach

使用代码的示例:

const array1 = [12, 3, 7];
const array2 = [];

const dispEls = (el, idx, array1) =>
  array2.push("exp (a[" + idx + "] = " + el + ") = " +
    Math.exp(el).toFixed(2));

array2.push("===== FOREACH");
let result_forEach = array1.forEach(dispEls);
array2.push("===== MAP");
let result_map = array1.map(dispEls);


console.dir(result_forEach)
console.dir(result_map)

返回的map数组是从push返回的值(索引,元素被推送到)

© www.soinside.com 2019 - 2024. All rights reserved.