map()与forEach的区别
<h4>问题1:map() 与 forEach()的区别</h4>
<h4>思考 :都是对于数组的一些方法</h4>
<h6>参考网址:<a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach">https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach</a></h6>
<hr />
<ul>
<li>
<h5>map((item,index,arr) = {})</h5>
<p>map() 方法创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后返回的结果。
参数:callback 函数会被自动传入三个参数:数组元素,元素索引,原数组本身。
map 不修改调用它的原数组本身(当然可以在 callback 执行时改变原数组)。</p>
<pre><code class="language-javascript">var array1 = [1, 4, 9, 16];
// pass a function to map
const map1 = array1.map(x => x * 2);
console.log(map1);
// expected output: Array [2, 8, 18, 32]</code></pre>
</li>
<li>
<h5>array.forEach(callback(currentValue, index, array){//do something}, this)</h5>
<p>forEach() 方法对数组的每个元素执行一次提供的函数。
array.forEach(callback(currentValue, index, array){
//do something
}, this)
callback 函数会被依次传入三个参数:
currentValue:数组当前项的值
index:数组当前项的索引
array:数组对象本身</p>
</li>
</ul>
<pre><code class="language-javascript">var array1 = ['a', 'b', 'c'];
array1.forEach(function(element) {
console.log(element);
});
// expected output: "a"
// expected output: "b"
// expected output: "c"</code></pre>
<h4>数组去重</h4>
<pre><code class="language-javascript">var a = [1,2,3,4,5,6,6];
var b = new Set(a)
console.log(b.size)
console.log([...b]) //去重后的数组</code></pre>