欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JS中的常見數(shù)組遍歷案例詳解(forEach,?map,?filter,?sort,?reduce,?every)

 更新時(shí)間:2023年05月16日 15:39:53   作者:kevozzy  
這篇文章主要介紹了JS中的常見數(shù)組遍歷方法詳解(forEach,?map,?filter,?sort,?reduce,?every),本篇講用實(shí)際案例詳解他們的語法和用法,需要的朋友可以參考下

在ES6的語法中,數(shù)組新添了好幾種新的和遍歷有關(guān)的方法。雖然這些函數(shù)本質(zhì)上都是語法糖,理論上說,離開他們一樣可以寫碼。但是他們的存在使我們的業(yè)務(wù)處理方便了太多,所以說熟練掌握他們?cè)趯?shí)際開發(fā)中是非常必要的。對(duì)于第一次見到他們的同學(xué)來說,他們也許不是特別容易理解,本篇講用實(shí)際案例詳解他們的語法和用法。

所有數(shù)組方式的共同點(diǎn):參數(shù)都接收一個(gè)回調(diào)函數(shù)

以下所有回調(diào)函數(shù)內(nèi)的參數(shù)都是形參。也就是說,用forEach舉個(gè)例子,你并不需要一定把參數(shù)寫成element,index,和array。你會(huì)看到我會(huì)用許多自定義的參數(shù)名來代表他們,你只需要按順序傳參數(shù)即可。

1. forEach

基本語法:

forEach((element, index, array) => { /* … */ }) // return undefined

element指數(shù)組中的每一個(gè)元素,index指各個(gè)元素相對(duì)應(yīng)的索引,array指數(shù)組本身。但是如果你通過arr.forEach()的方式來寫的話,第三個(gè)參數(shù)array往往不需要。forEach沒有返回值

首先,我認(rèn)為最容易理解,也最常使用的數(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有一個(gè)常見的用法,就是遍歷一個(gè)nodeList(節(jié)點(diǎn)集合),對(duì)dom中的多個(gè)對(duì)象進(jìn)行統(tǒng)一操作。請(qǐng)看下面這個(gè)例子。

         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')
        // 對(duì)數(shù)組進(jìn)行遍歷,數(shù)組中每有一個(gè)元素就添加一個(gè)dom對(duì)象
        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)
        })

以下是另外兩個(gè)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,賦予他們新的內(nèi)容,并且綁定事件
        const buttons = document.querySelectorAll('.div')
        buttons.forEach((button, index) => {
            button.textContent = '我是一個(gè)按鈕'
            button.addEventListener('click', () => {
                console.log('我是一個(gè)按鈕, 并且我的縮印是' + index)
            })
        })
     </script>
        // 根據(jù)剛才的inventors數(shù)組,計(jì)算所有科學(xué)家生命總長度    
        let totalYearsLived = 0
        inventors.forEach(function(inventor) {
            let yearLived = inventor.passed - inventor.year
            totalYearsLived += yearLived
        })
        console.log(totalYearsLived) // 861

2. map

基本語法:

let newArr = map((element, index, array) => { /* … */ })
// return new array

map和forEach類似,最大的區(qū)別是會(huì)返回一個(gè)全新的數(shù)組。不會(huì)改變?cè)瓟?shù)組,element, index,和array的意義于forEach相同。

下面這兩個(gè)例子將為闡述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的全名,并將他們組成一個(gè)新的數(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中每一個(gè)數(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 copy

filter是另一個(gè)語法和map以及forEach很相似的數(shù)組方法。filter中文是過濾,特別適用于提取一個(gè)數(shù)組中符合條件的數(shù)組。每輪遍歷返回一個(gè)布爾值,結(jié)果為true的元素會(huì)被添加到新數(shù)組中,最終filter將返回這個(gè)新數(shù)組

filter是我認(rèn)為第二常用,也極其好用的一個(gè)數(shù)組方式。因?yàn)楹芏鄷r(shí)候我們需要根據(jù)條件篩選一部分?jǐn)?shù)組元素,而這個(gè)時(shí)候filter會(huì)特別方便。對(duì)于新手來說,最大的難點(diǎn)是理解回調(diào)函數(shù)中的return值是一個(gè)布爾值,這個(gè)布爾值通常以一個(gè)表達(dá)式的形式出現(xiàn)。然而filter最終返回的是一個(gè)數(shù)組的淺拷貝。簡而言之,改變淺拷貝的元素值也會(huì)影響之前的數(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年之間的科學(xué)家
        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的科學(xué)家
        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的語法和前面的方法有所不同,你可以直接調(diào)用它,不傳任何參數(shù);也可以傳一個(gè)用于比較的回調(diào)函數(shù)。sort的用途是給一個(gè)數(shù)組中的元素排序,ab此分別指代第一個(gè)用于比較的元素和第二個(gè)用于比較的元素。返回值為排序后的原數(shù)組

如果沒有比較函數(shù),那么sort將會(huì)按照元素的Unicode位點(diǎn)進(jìn)行排序。也就是說:'Banana'會(huì)排在'Cat'前,因?yàn)閎比c要靠前。110也會(huì)排在20之前,因?yàn)?比2靠前。請(qǐng)看下面兩個(gè)例子

        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中傳入一個(gè)比較函數(shù),那么sort將會(huì)按照a和b的大小進(jìn)行排序,基本規(guī)則如下:

比較函數(shù)(a, b)返回值排序順序
> 0ab
< 0ab
=== 0保持ab的順序

簡而言之,比較函數(shù)每次執(zhí)行需要返回一個(gè)數(shù)字,如果這個(gè)數(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ù)字之間進(jìn)行比較,那么以上函數(shù)可以簡寫:
function compareFn(a, b){
    return a - b
}

這次,我們?cè)俅耸褂弥暗臄?shù)字?jǐn)?shù)組的例子排序,但是這次使用回調(diào)的比較函數(shù)。結(jié)果將會(huì)按照數(shù)字實(shí)際大小進(jìn)行排序:

        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)
// 返回一個(gè)類型不一定的結(jié)果

reduce可以說是數(shù)組方法里最難理解,也最特殊的一個(gè)函數(shù)了。

reduce同樣接受一個(gè)回調(diào)函數(shù)和一個(gè)初始值作為參數(shù),這個(gè)回調(diào)函數(shù)可以接受4個(gè)參數(shù),分別是上一個(gè)值(總值),當(dāng)前值,當(dāng)前索引,和數(shù)組,reduce有一個(gè)可選的第二個(gè)參數(shù),為初始值。如果不填寫,那遍歷將從索引1開始,也就是數(shù)組的第二個(gè)元素,因?yàn)榈谝粋€(gè)元素的初始值不存在,當(dāng)前索引的值也將為1。如果填寫初始值,那么第一輪遍歷的當(dāng)前索引為0,當(dāng)前元素為一個(gè)數(shù)組元素,上一個(gè)元素也將成為初始值。返回回調(diào)函數(shù)遍歷整個(gè)數(shù)組后的結(jié)果

reduce不是一個(gè)特別常用的數(shù)組方式,但在部分情況下,他可以大大減少代碼的復(fù)雜程度,我們將用多個(gè)例子來展現(xiàn)reduce的一些實(shí)際用途。

        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

第一眼看到上面這段代碼,你可能會(huì)有點(diǎn)摸不清頭腦,下面這個(gè)表格可以幫助你理解

回調(diào)次數(shù)previousValuecurrentValuecurrentIndexreturn value
第一輪遍歷1415
第二輪遍歷5982103
第三輪遍歷1031703273
第四輪遍歷273354308

我們的數(shù)組共有六個(gè)元素,所以將一共遍歷六次。上面的例子是前四輪的過程以及結(jié)果。下面有另外一個(gè)例子來表明如何用reduce來集合對(duì)象數(shù)組中的值:

        let shoppingCart = [
            {
                product: 'phone',
                qty: 1,
                price: 500,
            },
            {
                product: 'Screen Protector',
                qty: 1,
                price: 10,
            },
            {
                product: 'Memory Card',
                qty: 2,
                price: 20,
            },
        ];
        // 計(jì)算購物車內(nèi)的價(jià)格總和
        let total = shoppingCart.reduce(function (previousValue, currentValue) {
            return previousValue + currentValue.qty * currentValue.price;
        }, 0);
        console.log(total) // 550

以上是reduce的兩個(gè)比較基礎(chǔ)的用法,你也可以把它應(yīng)用在一些更復(fù)雜的場景當(dāng)中。還有一個(gè)比較常見的場景就是把一個(gè)數(shù)組中相同種類的對(duì)象歸為一類,形成一個(gè)新的數(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
  // 首先給每個(gè)存在的年齡段創(chuàng)建一個(gè)空數(shù)組
  // 然后用push將每個(gè)元素放入相應(yīng)的數(shù)組
  if (groupedPeople[age] == null) groupedPeople[age] = []
  groupedPeople[age].push(person)
  return groupedPeople
    }, {}) // 初始值是一個(gè)空對(duì)象,這樣才能使用增加屬性
    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

最終,我們將以一個(gè)比較簡單的函數(shù)收尾: every()。every方法用于檢查一個(gè)數(shù)組中是否所有元素都滿足條件。有任何一個(gè)不滿足條件,回調(diào)函數(shù)將返回false。如果所有遍歷都返回true,那么every最終將返回true

every自身的概念很好理解,我們用一個(gè)例子來闡述他的作用

        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個(gè)字母并且出生于1400年以后
        let checkInventors = inventors.every(inventor => {
            return inventor.last.length >= 4 && inventor.year>1400
        })
        console.log(checkInventors) // true

最后只有一個(gè)需要額外注意的是,今天所講的所有的數(shù)組方法,不會(huì)遍歷空的數(shù)組元素

console.log([1, , 3].every((x) => x !== undefined)); // true
console.log([2, , 2].every((x) => x === 2)); // true

以上就是ES6中的常見數(shù)組遍歷方式,掌握他們對(duì)業(yè)務(wù)至關(guān)重要,需要在合適的情況下多多練習(xí)。

到此這篇關(guān)于JS中的常見數(shù)組遍歷方法詳解(forEach, map, filter, sort, reduce, every)的文章就介紹到這了,更多相關(guān)js數(shù)組遍歷內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • JavaScript實(shí)現(xiàn)的簡單拖拽效果

    JavaScript實(shí)現(xiàn)的簡單拖拽效果

    這篇文章主要介紹了JavaScript實(shí)現(xiàn)的簡單拖拽效果,涉及javascript針對(duì)鼠標(biāo)事件與頁面樣式的操作技巧,需要的朋友可以參考下
    2015-06-06
  • js浮點(diǎn)數(shù)精確計(jì)算(加、減、乘、除)

    js浮點(diǎn)數(shù)精確計(jì)算(加、減、乘、除)

    本篇文章主要介紹了js浮點(diǎn)數(shù)精確計(jì)算(加、減、乘、除) 需要的朋友可以過來參考下,希望對(duì)大家有所幫助
    2013-12-12
  • 從jQuery.camelCase()學(xué)習(xí)string.replace() 函數(shù)學(xué)習(xí)

    從jQuery.camelCase()學(xué)習(xí)string.replace() 函數(shù)學(xué)習(xí)

    camelCase函數(shù)的功能就是將形如background-color轉(zhuǎn)化為駝峰表示法:backgroundColor。
    2011-09-09
  • 深入淺析var,let,const的異同點(diǎn)

    深入淺析var,let,const的異同點(diǎn)

    這篇文章主要介紹了var,let,const異同點(diǎn),文中較詳細(xì)的給大家介紹了let和const的相同點(diǎn)和不同點(diǎn),需要的朋友可以參考下
    2018-08-08
  • 最新評(píng)論