JS里的map与forEach遍历

map

返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。

var numbers = [3,2,6,3]
function func(num){
    return num * document.getElementById('mul').value
}
function myfun(){
    document.getElementById('demo').innerText=numbers.map(func)
}

  

forEach

对循环里面的元素进行处理,返回需要自己重构

var numbers = [3,2,6,3]   
function myfun(){
     var newnum = []
     numbers.forEach((item)=>{
     var a = document.getElementById('mul').value * item
     newnum.push(a)
     })  
    document.getElementById('demo').innerText=newnum          
}

上面两个例子的实现功能相同

原文地址:https://www.cnblogs.com/jack-liu6/p/8950398.html