2、數組中的forEach和map的區別
大多數狀況下,咱們都要對數組進行遍歷,而後常常用到的兩個方法就是forEach和map方法。
先來講說它們的共同點瀏覽器
相同點
- 都是循環遍歷數組中的每一項
- forEach和map方法裏每次執行匿名函數都支持3個參數,參數分別是item(當前每一項),index(索引值),arr(原數組)
- 匿名函數中的this都是指向window
- 只能遍歷數組
- 都不會改變原數組
區別
map方法
1.map方法返回一個新的數組,數組中的元素爲原始數組調用函數處理後的值。
2.map方法不會對空數組進行檢測,map方法不會改變原始數組。
3.瀏覽器支持:chrome、Safari1.5+、opera都支持,IE9+,markdown
array.map(function(item,index,arr){},thisValue) var arr = [0,2,4,6,8]; var str = arr.map(function(item,index,arr){ console.log(this); //window console.log("原數組arr:",arr); //注意這裏執行5次 return item/2; },this); console.log(str);//[0,1,2,3,4]
若arr爲空數組,則map方法返回的也是一個空數組。
forEach方法
1.forEach方法用來調用數組的每一個元素,將元素傳給回調函數
2.forEach對於空數組是不會調用回調函數的。函數
Array.forEach(function(item,index,arr){},this) var arr = [0,2,4,6,8]; var sum = 0; var str = arr.forEach(function(item,index,arr){ sum += item; console.log("sum的值爲:",sum); //0 2 6 12 20 console.log(this); //window },this) console.log(sum);//20 console.log(str); //undefined
不管arr是否是空數組,forEach返回的都是undefined。這個方法只是將數組中的每一項做爲callback的參數執行一次。post