javascript
JS中map()与forEach()的用法
JS中map()與forEach()的用法
相同點(diǎn):
1.都是循環(huán)遍歷數(shù)組中的每一項(xiàng)
2.每次執(zhí)行匿名函數(shù)都支持三個(gè)參數(shù),參數(shù)分別為item(當(dāng)前每一項(xiàng)),index(索引值),arr(原數(shù)組)
3.匿名函數(shù)中的this都是指向window
4.只能遍歷數(shù)組
不同點(diǎn):
map()
map方法返回一個(gè)新的數(shù)組,數(shù)組中的元素為原始數(shù)組調(diào)用函數(shù)處理后的值
也就是map()進(jìn)行處理之后返回一個(gè)新的數(shù)組
??注意:map()方法不會(huì)對(duì)空數(shù)組進(jìn)行檢測(cè)
map方法不會(huì)改變?cè)紨?shù)組
var arr = [0,2,4,6,8];var str = arr.map(function(item,index,arr){console.log(this); //Windowconsole.log(this);console.log(item);console.log('原數(shù)組arr:',arr); // 會(huì)執(zhí)行五次return item/2; },this);console.log(str); //[0,1,2,3,4]forEach
forEach方法用于調(diào)用數(shù)組的每個(gè)元素,將元素傳給回調(diào)函數(shù)
??注意: forEach對(duì)于空數(shù)組是不會(huì)調(diào)用回調(diào)函數(shù)的 ,
沒(méi)有返回一個(gè)新數(shù)組&沒(méi)有返回值
應(yīng)用場(chǎng)景:為一些相同的元素,綁定事件處理器!
不可鏈?zhǔn)秸{(diào)用?
var arr = [0,2,4,6,8] var sum =0; var str = arr.forEach(item,index,arr) { sum+= item; console.log("sum的值為:",sum); }我們先來(lái)看兩者之間的相同之處
var arr = ['a','b','c','d'];arr.forEach(function(item,index,arr){ //item表示數(shù)組中的每一項(xiàng),index標(biāo)識(shí)當(dāng)前項(xiàng)的下標(biāo),arr表示當(dāng)前數(shù)組console.log(item);console.log(index);console.log(arr);console.log(this); },123); //這里的123參數(shù),表示函數(shù)中的this指向,可寫(xiě)可不寫(xiě),如果不寫(xiě),則this指向windowarr.map(function(item,index,arr){ //參數(shù)含義同forEachconsole.log(item);console.log(index);console.log(arr);console.log(this); },123);運(yùn)行之后,可以看出兩者參數(shù)沒(méi)有任何的區(qū)別,除此之外兩者之間還有一個(gè)特性,就是不能停止里面的遍歷,除非程序報(bào)錯(cuò),那么兩者之間的區(qū)別在那里呢???
在于返回值!!!
var a = arr.forEach(function(item,index,arr){ return 123 }); var b = arr.map(function(item,index,arr){return 123 }); console.log(a); //undefined console.log(b); //[123,123,123,123]我們可以利用map的這個(gè)特性做哪些事情呢,比如
var b = arr.map(function(item,index,arr){return item+'a'; }); console.log(b); //["aa", "ba", "ca", "da"]?
// 之前我們的循環(huán)是這樣的 for (var index = 0; index < myArray.length; index++) { console.log(myArray[index]); } // 從ES5開(kāi)始提供這樣的for循環(huán) myArray.forEach(function (value) { console.log(value); }); // 在ES6我們還可以這樣任性 // 循環(huán)下標(biāo)或者key(for-in) for (var index in myArray) { // don't actually do this console.log(myArray[index]); } // 循環(huán)value(for-of) for (var value of myArray) { console.log(value); } // 甚至直接循環(huán)key和value,no problem for (var [key, value] of phoneBookMap) { console.log(key + "'s phone number is: " + value); } // 或者更者我們這樣“優(yōu)雅”的循環(huán)對(duì)象(貌似和ES6沒(méi)有關(guān)系) for (var key of Object.keys(someObject)) { console.log(key + ": " + someObject[key]); } // 現(xiàn)場(chǎng)實(shí)例,我們這樣使用 var items = [...]; items.forEach((item, i) => { if (item.status == 'new') this.apply(item, i) }); 《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專(zhuān)家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的JS中map()与forEach()的用法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: JavaScript之Set与Map
- 下一篇: 黑猫315十大行业乱象发布:背后真假套路