JS中的常見數(shù)組遍歷案例詳解(forEach,?map,?filter,?sort,?reduce,?every)
在ES6的語法中,數(shù)組新添了好幾種新的和遍歷有關的方法。雖然這些函數(shù)本質上都是語法糖,理論上說,離開他們一樣可以寫碼。但是他們的存在使我們的業(yè)務處理方便了太多,所以說熟練掌握他們在實際開發(fā)中是非常必要的。對于第一次見到他們的同學來說,他們也許不是特別容易理解,本篇講用實際案例詳解他們的語法和用法。
所有數(shù)組方式的共同點:參數(shù)都接收一個回調函數(shù)
以下所有回調函數(shù)內的參數(shù)都是形參。也就是說,用forEach舉個例子,你并不需要一定把參數(shù)寫成element,index,和array。你會看到我會用許多自定義的參數(shù)名來代表他們,你只需要按順序傳參數(shù)即可。
1. forEach
基本語法:
forEach((element, index, array) => { /* … */ }) // return undefinedelement指數(shù)組中的每一個元素,index指各個元素相對應的索引,array指數(shù)組本身。但是如果你通過arr.forEach()的方式來寫的話,第三個參數(shù)array往往不需要。forEach沒有返回值
首先,我認為最容易理解,也最常使用的數(shù)組方法: forEach。forEach基本上就是for循環(huán)的代替品,最適合用于循環(huán)數(shù)組,也可以用于循環(huán)其他可循環(huán)數(shù)據(jù)(比如nodelist,Map和Set)。本身沒有任何返回值,僅根據(jù)數(shù)據(jù)數(shù)量做循環(huán)操作。
forEach有一個常見的用法,就是遍歷一個nodeList(節(jié)點集合),對dom中的多個對象進行統(tǒng)一操作。請看下面這個例子。
const inventors = [
{ first: 'Albert', last: 'Einstein', year: 1879, passed: 1955 },
{ first: 'Isaac', last: 'Newton', year: 1643, passed: 1727 },
{ first: 'Galileo', last: 'Galilei', year: 1564, passed: 1642 },
{ first: 'Marie', last: 'Curie', year: 1867, passed: 1934 },
{ first: 'Johannes', last: 'Kepler', year: 1571, passed: 1630 },
{ first: 'Nicolaus', last: 'Copernicus', year: 1473, passed: 1543 },
{ first: 'Max', last: 'Planck', year: 1858, passed: 1947 },
{ first: 'Katherine', last: 'Blodgett', year: 1898, passed: 1979 },
{ first: 'Ada', last: 'Lovelace', year: 1815, passed: 1852 },
{ first: 'Sarah E.', last: 'Goode', year: 1855, passed: 1905 },
{ first: 'Lise', last: 'Meitner', year: 1878, passed: 1968 },
{ first: 'Hanna', last: 'Hammarstr?m', year: 1829, passed: 1909 }
];
// 選擇dom元素
const list = document.querySelector('.list')
// 對數(shù)組進行遍歷,數(shù)組中每有一個元素就添加一個dom對象
inventors.forEach(function(inventor, index) {
const listItem = document.createElement('li')
listItem.textContent = `${index}: ${inventor.first},
born ${inventor.year}`
list.appendChild(listItem)
})
// 箭頭函數(shù)寫法:
inventors.forEach((inventor, index) => {
const listItem = document.createElement('li')
listItem.textContent = `${index}: ${inventor.first},
born ${inventor.year}`
list.appendChild(listItem)
})以下是另外兩個forEach的使用場景:
<button class="div">click me</button>
<button class="div">click me</button>
<button class="div">click me</button>
<button class="div">click me</button>
<button class="div">click me</button>
<script>
// 獲取所有button,賦予他們新的內容,并且綁定事件
const buttons = document.querySelectorAll('.div')
buttons.forEach((button, index) => {
button.textContent = '我是一個按鈕'
button.addEventListener('click', () => {
console.log('我是一個按鈕, 并且我的縮印是' + index)
})
})
</script> // 根據(jù)剛才的inventors數(shù)組,計算所有科學家生命總長度
let totalYearsLived = 0
inventors.forEach(function(inventor) {
let yearLived = inventor.passed - inventor.year
totalYearsLived += yearLived
})
console.log(totalYearsLived) // 8612. map
基本語法:
let newArr = map((element, index, array) => { /* … */ })
// return new arraymap和forEach類似,最大的區(qū)別是會返回一個全新的數(shù)組。不會改變原數(shù)組,element, index,和array的意義于forEach相同。
下面這兩個例子將為闡述map的基本用法:
const inventors = [
{ first: 'Albert', last: 'Einstein', year: 1879, passed: 1955 },
{ first: 'Isaac', last: 'Newton', year: 1643, passed: 1727 },
{ first: 'Galileo', last: 'Galilei', year: 1564, passed: 1642 },
{ first: 'Marie', last: 'Curie', year: 1867, passed: 1934 },
{ first: 'Johannes', last: 'Kepler', year: 1571, passed: 1630 },
{ first: 'Nicolaus', last: 'Copernicus', year: 1473, passed: 1543 },
{ first: 'Max', last: 'Planck', year: 1858, passed: 1947 },
{ first: 'Katherine', last: 'Blodgett', year: 1898, passed: 1979 },
{ first: 'Ada', last: 'Lovelace', year: 1815, passed: 1852 },
{ first: 'Sarah E.', last: 'Goode', year: 1855, passed: 1905 },
{ first: 'Lise', last: 'Meitner', year: 1878, passed: 1968 },
{ first: 'Hanna', last: 'Hammarstr?m', year: 1829, passed: 1909 }
];
// 得到所有inventor的全名,并將他們組成一個新的數(shù)組
let fullnameArr = inventors.map(function(inventor) {
return inventor.first + ' ' + inventor.last
})
// 箭頭函數(shù)寫法
let fullnameArr = inventors.map(inventor => inventor.first + ' ' + inventor.last) const numArr = [1, 4, 98, 170, 35, 87]
// 得到numArr中每一個數(shù)字的2倍
let doubleNumArr = numArr.map(num => num*2)
console.log(doubleNumArr) // [2, 8, 196, 340, 70, 174]3. filter
基本語法:
filter((element, index, array) => { /* … */ } )
// return shallow copyfilter是另一個語法和map以及forEach很相似的數(shù)組方法。filter中文是過濾,特別適用于提取一個數(shù)組中符合條件的數(shù)組。每輪遍歷返回一個布爾值,結果為true的元素會被添加到新數(shù)組中,最終filter將返回這個新數(shù)組
filter是我認為第二常用,也極其好用的一個數(shù)組方式。因為很多時候我們需要根據(jù)條件篩選一部分數(shù)組元素,而這個時候filter會特別方便。對于新手來說,最大的難點是理解回調函數(shù)中的return值是一個布爾值,這個布爾值通常以一個表達式的形式出現(xiàn)。然而filter最終返回的是一個數(shù)組的淺拷貝。簡而言之,改變淺拷貝的元素值也會影響之前的數(shù)組的元素。
const inventors = [
{ first: 'Albert', last: 'Einstein', year: 1879, passed: 1955 },
{ first: 'Isaac', last: 'Newton', year: 1643, passed: 1727 },
{ first: 'Galileo', last: 'Galilei', year: 1564, passed: 1642 },
{ first: 'Marie', last: 'Curie', year: 1867, passed: 1934 },
{ first: 'Johannes', last: 'Kepler', year: 1571, passed: 1630 },
{ first: 'Nicolaus', last: 'Copernicus', year: 1473, passed: 1543 },
{ first: 'Max', last: 'Planck', year: 1858, passed: 1947 },
{ first: 'Katherine', last: 'Blodgett', year: 1898, passed: 1979 },
{ first: 'Ada', last: 'Lovelace', year: 1815, passed: 1852 },
{ first: 'Sarah E.', last: 'Goode', year: 1855, passed: 1905 },
{ first: 'Lise', last: 'Meitner', year: 1878, passed: 1968 },
{ first: 'Hanna', last: 'Hammarstr?m', year: 1829, passed: 1909 }
];
// 獲取所有出生在1500年和1600年之間的科學家
const fifteen = inventors.filter(function(inventor) {
return inventor.year >= 1500 && inventor.year < 1600
})
// 箭頭函數(shù)寫法
const fifteen = inventors.filter(inventor => inventor.year >= 1500 && inventor.year < 1600)
console.log(fifteen)
// 例子2:獲取所有名字中有字母a的科學家
const nameHasA = inventors.filter(function(inventor) {
return inventor.last.includes('a')
})
// 箭頭函數(shù)寫法
const nameHasA = inventors.filter(inventor => inventor.last.includes('a'))
console.log(nameHasA)4. sort
基本語法:
sort()
sort((a, b) => { /* … */ } )
// 返回sort后被改變的原數(shù)組sort的語法和前面的方法有所不同,你可以直接調用它,不傳任何參數(shù);也可以傳一個用于比較的回調函數(shù)。sort的用途是給一個數(shù)組中的元素排序,a和b在此分別指代第一個用于比較的元素和第二個用于比較的元素。返回值為排序后的原數(shù)組
如果沒有比較函數(shù),那么sort將會按照元素的Unicode位點進行排序。也就是說:'Banana'會排在'Cat'前,因為b比c要靠前。110也會排在20之前,因為1比2靠前。請看下面兩個例子
const numArr = [1, 4, 98, 170, 35, 87]
// 純數(shù)字排序
const sortNoParams = numArr.sort()
console.log(sortNoParams) // [1, 170, 35, 4, 87, 98]
const nameArr = ['Hanna', 'Meitner', 'Blodgett', 'Nicolaus', 'Einstein']
// 字符串排序
const newNameArr = nameArr.sort()
console.log(newNameArr) // ['Blodgett', 'Einstein', 'Hanna', 'Meitner', 'Nicolaus']但是,如果你在sort中傳入一個比較函數(shù),那么sort將會按照a和b的大小進行排序,基本規(guī)則如下:
| 比較函數(shù)(a, b)返回值 | 排序順序 |
|---|---|
| > 0 | a在b后 |
| < 0 | a在b前 |
| === 0 | 保持a和b的順序 |
簡而言之,比較函數(shù)每次執(zhí)行需要返回一個數(shù)字,如果這個數(shù)字大于0,數(shù)組按升序排序;如果小于0,則按降序排序。如果等于0,則順序不變。傳統(tǒng)上講,我們一般返回1和-1來分別代表大于0和小于0的情況。使用方式如下:
function compareFn(a, b) {
if (在某些排序規(guī)則中,a 小于 b) {
return -1;
}
if (在這一排序規(guī)則下,a 大于 b) {
return 1;
}
// a 一定等于 b
return 0;
}
通常我們把返回值寫為1和-1來代表返回值是否大于0
但如果是純數(shù)字之間進行比較,那么以上函數(shù)可以簡寫:
function compareFn(a, b){
return a - b
}這次,我們再此使用之前的數(shù)字數(shù)組的例子排序,但是這次使用回調的比較函數(shù)。結果將會按照數(shù)字實際大小進行排序:
const numArr = [1, 4, 98, 170, 35, 87]
const sortedArr = numArr.sort(function(a, b) {
return a - b
})
// 箭頭函數(shù)寫法
const sortedArr = numArr.sort((a, b) => a - b)
console.log(sortedArr) // [1, 4, 35, 87, 98, 170]
const nameArr = ['Hanna', 'Meitner', 'Blodgett', 'Nicolaus', 'Einstein']
const sortName = nameArr.sort((a, b) => {
if(a < b) {
return -1
} else if(a > b) {
return 1
}
return 0
})
console.log(sortName) // ['Blodgett', 'Einstein', 'Hanna', 'Meitner', 'Nicolaus']5. reduce
基本語法:
reduce((previousValue, currentValue, currentIndex, array) => { /* … */ }
, initialValue)
// 返回一個類型不一定的結果reduce可以說是數(shù)組方法里最難理解,也最特殊的一個函數(shù)了。
reduce同樣接受一個回調函數(shù)和一個初始值作為參數(shù),這個回調函數(shù)可以接受4個參數(shù),分別是上一個值(總值),當前值,當前索引,和數(shù)組,reduce有一個可選的第二個參數(shù),為初始值。如果不填寫,那遍歷將從索引1開始,也就是數(shù)組的第二個元素,因為第一個元素的初始值不存在,當前索引的值也將為1。如果填寫初始值,那么第一輪遍歷的當前索引為0,當前元素為一個數(shù)組元素,上一個元素也將成為初始值。返回回調函數(shù)遍歷整個數(shù)組后的結果
reduce不是一個特別常用的數(shù)組方式,但在部分情況下,他可以大大減少代碼的復雜程度,我們將用多個例子來展現(xiàn)reduce的一些實際用途。
const numArr = [1, 4, 98, 170, 35, 87]
// 得到numArr的元素的和
let sum = numArr.reduce((previous, current) => {
return previous + current
})
console.log(sum) // 395
// 如果最初值存在的話
let withInitial = numArr.reduce((previous, current) => {
return previous + current
}, 100)
console.log(withInitial) // 495第一眼看到上面這段代碼,你可能會有點摸不清頭腦,下面這個表格可以幫助你理解
| 回調次數(shù) | previousValue | currentValue | currentIndex | return value | |
|---|---|---|---|---|---|
| 第一輪遍歷 | 1 | 4 | 1 | 5 | |
| 第二輪遍歷 | 5 | 98 | 2 | 103 | |
| 第三輪遍歷 | 103 | 170 | 3 | 273 | |
| 第四輪遍歷 | 273 | 35 | 4 | 308 |
我們的數(shù)組共有六個元素,所以將一共遍歷六次。上面的例子是前四輪的過程以及結果。下面有另外一個例子來表明如何用reduce來集合對象數(shù)組中的值:
let shoppingCart = [
{
product: 'phone',
qty: 1,
price: 500,
},
{
product: 'Screen Protector',
qty: 1,
price: 10,
},
{
product: 'Memory Card',
qty: 2,
price: 20,
},
];
// 計算購物車內的價格總和
let total = shoppingCart.reduce(function (previousValue, currentValue) {
return previousValue + currentValue.qty * currentValue.price;
}, 0);
console.log(total) // 550以上是reduce的兩個比較基礎的用法,你也可以把它應用在一些更復雜的場景當中。還有一個比較常見的場景就是把一個數(shù)組中相同種類的對象歸為一類,形成一個新的數(shù)組。
const people = [
{ name: 'Kyle', age: 26 },
{ name: 'John', age: 31 },
{ name: 'Sally', age: 42 },
{ name: 'Jill', age: 42 },
]
// 把年齡相同的人分為一組
const peopleGroupedByAge = people.reduce((groupedPeople, person) => {
const age = person.age
// 首先給每個存在的年齡段創(chuàng)建一個空數(shù)組
// 然后用push將每個元素放入相應的數(shù)組
if (groupedPeople[age] == null) groupedPeople[age] = []
groupedPeople[age].push(person)
return groupedPeople
}, {}) // 初始值是一個空對象,這樣才能使用增加屬性
console.log(peopleGroupedByAge)
/*
{
26: [{ name: 'Kyle', age: 26 }],
31: [{ name: 'John', age: 31 }],
42: [
{ name: 'Sally', age: 42 },
{ name: 'Jill', age: 42 }
]
}
*/6. every
基本語法:
every((element, index, array) => { /* … */ } ) // return boolean最終,我們將以一個比較簡單的函數(shù)收尾: every()。every方法用于檢查一個數(shù)組中是否所有元素都滿足條件。有任何一個不滿足條件,回調函數(shù)將返回false。如果所有遍歷都返回true,那么every最終將返回true
every自身的概念很好理解,我們用一個例子來闡述他的作用
const inventors = [
{ first: 'Albert', last: 'Einstein', year: 1879, passed: 1955 },
{ first: 'Isaac', last: 'Newton', year: 1643, passed: 1727 },
{ first: 'Galileo', last: 'Galilei', year: 1564, passed: 1642 },
{ first: 'Marie', last: 'Curie', year: 1867, passed: 1934 },
{ first: 'Johannes', last: 'Kepler', year: 1571, passed: 1630 },
{ first: 'Nicolaus', last: 'Copernicus', year: 1473, passed: 1543 },
{ first: 'Max', last: 'Planck', year: 1858, passed: 1947 },
{ first: 'Katherine', last: 'Blodgett', year: 1898, passed: 1979 },
{ first: 'Ada', last: 'Lovelace', year: 1815, passed: 1852 },
{ first: 'Sarah E.', last: 'Goode', year: 1855, passed: 1905 },
{ first: 'Lise', last: 'Meitner', year: 1878, passed: 1968 },
{ first: 'Hanna', last: 'Hammarstr?m', year: 1829, passed: 1909 }
];
// 檢查是不是所有發(fā)明家的last name都至少4個字母并且出生于1400年以后
let checkInventors = inventors.every(inventor => {
return inventor.last.length >= 4 && inventor.year>1400
})
console.log(checkInventors) // true最后只有一個需要額外注意的是,今天所講的所有的數(shù)組方法,不會遍歷空的數(shù)組元素
console.log([1, , 3].every((x) => x !== undefined)); // true console.log([2, , 2].every((x) => x === 2)); // true
以上就是ES6中的常見數(shù)組遍歷方式,掌握他們對業(yè)務至關重要,需要在合適的情況下多多練習。
到此這篇關于JS中的常見數(shù)組遍歷方法詳解(forEach, map, filter, sort, reduce, every)的文章就介紹到這了,更多相關js數(shù)組遍歷內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
- JS中filter( )數(shù)組過濾器的使用
- JavaScript遍歷數(shù)組的三種方法map、forEach與filter實例詳解
- JavaScript 數(shù)組some()和filter()的用法及區(qū)別
- JavaScript中find()、findIndex()、filter()、indexOf()處理數(shù)組方法的具體區(qū)別詳解
- js 數(shù)組 find,some,filter,reduce區(qū)別詳解
- JavaScript數(shù)組常用方法find、findIndex、filter、map、flatMap及some詳解
- JavaScript 數(shù)組的常用方法find 和 filter詳解及區(qū)別介紹
- JavaScript數(shù)組方法push()、forEach()、filter()、sort()實戰(zhàn)教程
相關文章
使用?JavaScript?Promise?讀取?Github?用戶數(shù)據(jù)
這篇文章主要介紹了使用JavaScript?Promise讀取Github用戶數(shù)據(jù),文章圍繞主題展開詳細的內容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-08-08
JavaScript高級程序設計閱讀筆記(十六) javascript檢測瀏覽器和操作系統(tǒng)-detect.js
javascript檢測瀏覽器和操作系統(tǒng) detect.js使用介紹,需要的朋友可以參考下2012-08-08
easywasmplayer實現(xiàn)視頻流播放示例詳解
這篇文章主要為大家介紹了easywasmplayer實現(xiàn)視頻流播放示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-09-09
純js網頁畫板(Graphics)類簡介及實現(xiàn)代碼
今天需要在網頁上畫一個圖譜,想到用JS,經過學習,和網上搜索,經過整理優(yōu)化得到下面代碼,注意不是用HTML5的canvas,而是用的純js,需要了解的朋友可以參考下2012-12-12

