ES5中forEach、map 、filter對比

ES5中forEach、map 、filter對比

forEach

foreach方法用於循環遍歷數組

 var arr = [1,4,3,2,6,3,2,2,4,8]
 		//					  值	下標				
        arr.forEach(function(item,index){E
            console.log(item,index)
        })
        遍歷數組中的每一個

在這裏插入圖片描述

map

map方法是遍歷數組,返回一個經過加工後的一個新數組

 var arr = [1,4,3,2,6,3,2,2,4,8]
        var arr1 = arr.map(function(item,index){
        	//將每一個值都加10
            return item + 10
        })
        console.log(arr1)

在這裏插入圖片描述

filter

filter方法是遍歷數組返回一個經過判斷過程,過濾後的一個新數組

 var arr = [1,4,3,2,6,3,2,2,4,8]
        var arr2 = arr.filter(function(item,index){
            //判斷是否爲大於等於4的數字,如果是便添加到新數組中
            return item >= 4
        })
        console.log(arr2)

在這裏插入圖片描述
總結
總的來說雖然三個都是遍歷數組的方法,但用處大不一樣:

Array.prototype.forEach(function(item,index){})遍歷數組
Array.prototype.map(function(item,index){})遍歷數組返回一個經過操作後的新數組
Array.prototype.filter(function(item,index){})遍歷數組返回一個經過判斷過濾後的新數組

~~~~~~~~~~~~ end ~~~~~~~~~~~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章