翼度科技»论坛 编程开发 JavaScript 查看内容

JS中的常见数组遍历案例详解(forEach, map, filter, sort, reduce, ev

5

主题

5

帖子

15

积分

新手上路

Rank: 1

积分
15
在ES6的语法中,数组新添了好几种新的和遍历有关的方法。虽然这些函数本质上都是语法糖,理论上说,离开他们一样可以写码。但是他们的存在使我们的业务处理方便了太多,所以说熟练掌握他们在实际开发中是非常必要的。对于第一次见到他们的同学来说,他们也许不是特别容易理解,本篇讲用实际案例详解他们的语法和用法。
  1. 所有数组方式的共同点:参数都接收一个回调函数
复制代码
以下所有回调函数内的参数都是形参。也就是说,用forEach举个例子,你并不需要一定把参数写成element,index,和array。你会看到我会用许多自定义的参数名来代表他们,你只需要按顺序传参数即可

1. forEach

基本语法:
  1. forEach((element, index, array) => { /* … */ }) // return undefined
复制代码
  1. element指数组中的每一个元素,index指各个元素相对应的索引,array指数组本身。但是如果你通过arr.forEach()的方式来写的话,第三个参数array往往不需要。forEach没有返回值
复制代码
首先,我认为最容易理解,也最常使用的数组方法: forEach。forEach基本上就是for循环的代替品,最适合用于循环数组,也可以用于循环其他可循环数据(比如nodelist,Map和Set)。本身没有任何返回值,仅根据数据数量做循环操作。
forEach有一个常见的用法,就是遍历一个nodeList(节点集合),对dom中的多个对象进行统一操作。请看下面这个例子。
  1.          const inventors = [
  2.             { first: 'Albert', last: 'Einstein', year: 1879, passed: 1955 },
  3.             { first: 'Isaac', last: 'Newton', year: 1643, passed: 1727 },
  4.             { first: 'Galileo', last: 'Galilei', year: 1564, passed: 1642 },
  5.             { first: 'Marie', last: 'Curie', year: 1867, passed: 1934 },
  6.             { first: 'Johannes', last: 'Kepler', year: 1571, passed: 1630 },
  7.             { first: 'Nicolaus', last: 'Copernicus', year: 1473, passed: 1543 },
  8.             { first: 'Max', last: 'Planck', year: 1858, passed: 1947 },
  9.             { first: 'Katherine', last: 'Blodgett', year: 1898, passed: 1979 },
  10.             { first: 'Ada', last: 'Lovelace', year: 1815, passed: 1852 },
  11.             { first: 'Sarah E.', last: 'Goode', year: 1855, passed: 1905 },
  12.             { first: 'Lise', last: 'Meitner', year: 1878, passed: 1968 },
  13.             { first: 'Hanna', last: 'Hammarström', year: 1829, passed: 1909 }
  14.         ];
  15.         // 选择dom元素
  16.         const list = document.querySelector('.list')
  17.         // 对数组进行遍历,数组中每有一个元素就添加一个dom对象
  18.         inventors.forEach(function(inventor, index) {
  19.             const listItem = document.createElement('li')
  20.             listItem.textContent = `${index}: ${inventor.first},
  21.             born ${inventor.year}`
  22.             list.appendChild(listItem)
  23.         })
  24.         // 箭头函数写法:
  25.         inventors.forEach((inventor, index) => {
  26.             const listItem = document.createElement('li')
  27.             listItem.textContent = `${index}: ${inventor.first},
  28.             born ${inventor.year}`
  29.             list.appendChild(listItem)
  30.         })
复制代码
以下是另外两个forEach的使用场景:
  1.     <button class="div">click me</button>
  2.     <button class="div">click me</button>
  3.     <button class="div">click me</button>
  4.     <button class="div">click me</button>
  5.     <button class="div">click me</button>        
  6.       <script>
  7.         // 获取所有button,赋予他们新的内容,并且绑定事件
  8.         const buttons = document.querySelectorAll('.div')
  9.         buttons.forEach((button, index) => {
  10.             button.textContent = '我是一个按钮'
  11.             button.addEventListener('click', () => {
  12.                 console.log('我是一个按钮, 并且我的缩印是' + index)
  13.             })
  14.         })
  15.      </script>
复制代码
  1.         // 根据刚才的inventors数组,计算所有科学家生命总长度   
  2.         let totalYearsLived = 0
  3.         inventors.forEach(function(inventor) {
  4.             let yearLived = inventor.passed - inventor.year
  5.             totalYearsLived += yearLived
  6.         })
  7.         console.log(totalYearsLived) // 861
复制代码
2. map

基本语法:
  1. let newArr = map((element, index, array) => { /* … */ })
  2. // return new array
复制代码
  1. map和forEach类似,最大的区别是会返回一个全新的数组。不会改变原数组,element, index,和array的意义于forEach相同。
复制代码
下面这两个例子将为阐述map的基本用法:
  1.         const inventors = [
  2.             { first: 'Albert', last: 'Einstein', year: 1879, passed: 1955 },
  3.             { first: 'Isaac', last: 'Newton', year: 1643, passed: 1727 },
  4.             { first: 'Galileo', last: 'Galilei', year: 1564, passed: 1642 },
  5.             { first: 'Marie', last: 'Curie', year: 1867, passed: 1934 },
  6.             { first: 'Johannes', last: 'Kepler', year: 1571, passed: 1630 },
  7.             { first: 'Nicolaus', last: 'Copernicus', year: 1473, passed: 1543 },
  8.             { first: 'Max', last: 'Planck', year: 1858, passed: 1947 },
  9.             { first: 'Katherine', last: 'Blodgett', year: 1898, passed: 1979 },
  10.             { first: 'Ada', last: 'Lovelace', year: 1815, passed: 1852 },
  11.             { first: 'Sarah E.', last: 'Goode', year: 1855, passed: 1905 },
  12.             { first: 'Lise', last: 'Meitner', year: 1878, passed: 1968 },
  13.             { first: 'Hanna', last: 'Hammarström', year: 1829, passed: 1909 }
  14.         ];
  15.         // 得到所有inventor的全名,并将他们组成一个新的数组
  16.         let fullnameArr = inventors.map(function(inventor) {
  17.             return inventor.first + ' ' + inventor.last
  18.         })
  19.         // 箭头函数写法
  20.         let fullnameArr = inventors.map(inventor => inventor.first + ' ' +   inventor.last)
复制代码
  1.         const numArr = [1, 4, 98, 170, 35, 87]
  2.         // 得到numArr中每一个数字的2倍
  3.         let doubleNumArr = numArr.map(num => num*2)
  4.         console.log(doubleNumArr) //  [2, 8, 196, 340, 70, 174]
复制代码
3. filter

基本语法:
  1. filter((element, index, array) => { /* … */ } )
  2. // return shallow copy
复制代码
  1. filter是另一个语法和map以及forEach很相似的数组方法。filter中文是过滤,特别适用于提取一个数组中符合条件的数组。每轮遍历返回一个布尔值,结果为true的元素会被添加到新数组中,最终filter将返回这个新数组
复制代码
filter是我认为第二常用,也极其好用的一个数组方式。因为很多时候我们需要根据条件筛选一部分数组元素,而这个时候filter会特别方便。对于新手来说,最大的难点是理解回调函数中的return值是一个布尔值,这个布尔值通常以一个表达式的形式出现。然而filter最终返回的是一个数组的浅拷贝。简而言之,改变浅拷贝的元素值也会影响之前的数组的元素。
  1.         const inventors = [
  2.             { first: 'Albert', last: 'Einstein', year: 1879, passed: 1955 },
  3.             { first: 'Isaac', last: 'Newton', year: 1643, passed: 1727 },
  4.             { first: 'Galileo', last: 'Galilei', year: 1564, passed: 1642 },
  5.             { first: 'Marie', last: 'Curie', year: 1867, passed: 1934 },
  6.             { first: 'Johannes', last: 'Kepler', year: 1571, passed: 1630 },
  7.             { first: 'Nicolaus', last: 'Copernicus', year: 1473, passed: 1543 },
  8.             { first: 'Max', last: 'Planck', year: 1858, passed: 1947 },
  9.             { first: 'Katherine', last: 'Blodgett', year: 1898, passed: 1979 },
  10.             { first: 'Ada', last: 'Lovelace', year: 1815, passed: 1852 },
  11.             { first: 'Sarah E.', last: 'Goode', year: 1855, passed: 1905 },
  12.             { first: 'Lise', last: 'Meitner', year: 1878, passed: 1968 },
  13.             { first: 'Hanna', last: 'Hammarström', year: 1829, passed: 1909 }
  14.         ];
  15.         // 获取所有出生在1500年和1600年之间的科学家
  16.         const fifteen = inventors.filter(function(inventor) {
  17.             return inventor.year >= 1500 && inventor.year < 1600
  18.         })
  19.         // 箭头函数写法
  20.         const fifteen = inventors.filter(inventor => inventor.year >= 1500 && inventor.year < 1600)
  21.         console.log(fifteen)
  22.         // 例子2:获取所有名字中有字母a的科学家
  23.         const nameHasA = inventors.filter(function(inventor) {
  24.            return inventor.last.includes('a')
  25.         })
  26.         // 箭头函数写法
  27.         const nameHasA = inventors.filter(inventor => inventor.last.includes('a'))
  28.         console.log(nameHasA)
复制代码
4. sort

基本语法:
  1. sort()
  2. sort((a, b) => { /* … */ } )
  3. // 返回sort后被改变的原数组
复制代码
  1. sort的语法和前面的方法有所不同,你<strong>可以直接调用</strong>它,不传任何参数;也可以传一个<strong>用于比较的回调函数</strong>。sort的用途是给一个数组中的元素排序,<strong>a</strong>和<strong>b</strong><strong>在</strong>此分别指代第一个用于<strong>比较的元素</strong>和第二个用于比较的元素。<strong>返回值为排序后的原数组</strong>
复制代码
如果没有比较函数,那么sort将会按照元素的Unicode位点进行排序。也就是说:'Banana'会排在'Cat'前,因为b比c要靠前。110也会排在20之前,因为1比2靠前。请看下面两个例子
  1.         const numArr = [1, 4, 98, 170, 35, 87]
  2.         // 纯数字排序
  3.         const sortNoParams = numArr.sort()
  4.         console.log(sortNoParams) // [1, 170, 35, 4, 87, 98]
  5.         const nameArr = ['Hanna', 'Meitner', 'Blodgett', 'Nicolaus', 'Einstein']
  6.         // 字符串排序
  7.         const newNameArr = nameArr.sort()
  8.         console.log(newNameArr) // ['Blodgett', 'Einstein', 'Hanna', 'Meitner', 'Nicolaus']
复制代码
但是,如果你在sort中传入一个比较函数,那么sort将会按照a和b的大小进行排序,基本规则如下:
比较函数(a, b)返回值排序顺序> 0
  1. a
复制代码
  1. b
复制代码
后< 0
  1. a
复制代码
  1. b
复制代码
前=== 0保持
  1. a
复制代码
  1. b
复制代码
的顺序简而言之,比较函数每次执行需要返回一个数字,如果这个数字大于0,数组按升序排序;如果小于0,则按降序排序。如果等于0,则顺序不变。传统上讲,我们一般返回1和-1来分别代表大于0和小于0的情况。使用方式如下:
  1. function compareFn(a, b) {
  2.   if (在某些排序规则中,a 小于 b) {
  3.     return -1;
  4.   }
  5.   if (在这一排序规则下,a 大于 b) {
  6.     return 1;
  7.   }
  8.   // a 一定等于 b
  9.   return 0;
  10. }
  11. 通常我们把返回值写为1和-1来代表返回值是否大于0
  12. 但如果是纯数字之间进行比较,那么以上函数可以简写:
  13. function compareFn(a, b){
  14.     return a - b
  15. }
复制代码
这次,我们再此使用之前的数字数组的例子排序,但是这次使用回调的比较函数。结果将会按照数字实际大小进行排序:
  1.         const numArr = [1, 4, 98, 170, 35, 87]
  2.         const sortedArr = numArr.sort(function(a, b) {
  3.             return a - b
  4.         })
  5.         // 箭头函数写法
  6.         const sortedArr = numArr.sort((a, b) => a - b)
  7.         console.log(sortedArr) // [1, 4, 35, 87, 98, 170]
  8.         const nameArr = ['Hanna', 'Meitner', 'Blodgett', 'Nicolaus', 'Einstein']
  9.         const sortName = nameArr.sort((a, b) => {
  10.             if(a < b) {
  11.                 return -1
  12.             } else if(a > b) {
  13.                 return 1
  14.             }
  15.             return 0
  16.         })
  17.         console.log(sortName) //  ['Blodgett', 'Einstein', 'Hanna', 'Meitner', 'Nicolaus']
复制代码
5. reduce

基本语法:
  1. reduce((previousValue, currentValue, currentIndex, array) => { /* … */ }
  2. , initialValue)
  3. // 返回一个类型不一定的结果
复制代码
reduce可以说是数组方法里最难理解,也最特殊的一个函数了。
  1. reduce同样接受一个<strong>回调函数</strong>和一个<strong>初始值</strong>作为参数,这个回调函数可以接受4个参数,分别是<strong>上一个值(总值)</strong>,<strong>当前值</strong>,<strong>当前索引</strong>,和<strong>数组</strong>,reduce有一个<strong>可选的第二个参数</strong>,为初始值。<strong>如果不填写,那遍历将从索引1开始,也就是数组的第二个元素</strong>,因为第一个元素的初始值不存在,当前索引的值也将为1。如果填写初始值,那么第一轮遍历的当前索引为0,当前元素为一个数组元素,上一个元素也将成为初始值。<strong>返回回调函数遍历整个数组后的结果</strong>
复制代码
reduce不是一个特别常用的数组方式,但在部分情况下,他可以大大减少代码的复杂程度,我们将用多个例子来展现reduce的一些实际用途。
  1.         const numArr = [1, 4, 98, 170, 35, 87]
  2.         // 得到numArr的元素的和
  3.         let sum = numArr.reduce((previous, current) => {
  4.             return previous + current
  5.         })
  6.         console.log(sum) // 395   
  7.         // 如果最初值存在的话
  8.         let withInitial = numArr.reduce((previous, current) => {
  9.             return previous + current
  10.         }, 100)
  11.         console.log(withInitial) // 495
复制代码
第一眼看到上面这段代码,你可能会有点摸不清头脑,下面这个表格可以帮助你理解
回调次数previousValuecurrentValuecurrentIndexreturn value第一轮遍历
  1. 1
复制代码
4
  1. 1
复制代码
  1. 5
复制代码
第二轮遍历
  1. 5
复制代码
  1. 98
复制代码
  1. 2
复制代码
103第三轮遍历103170
  1. 3
复制代码
273第四轮遍历27335
  1. 4
复制代码
308我们的数组共有六个元素,所以将一共遍历六次。上面的例子是前四轮的过程以及结果。下面有另外一个例子来表明如何用reduce来集合对象数组中的值:
  1.         let shoppingCart = [
  2.             {
  3.                 product: 'phone',
  4.                 qty: 1,
  5.                 price: 500,
  6.             },
  7.             {
  8.                 product: 'Screen Protector',
  9.                 qty: 1,
  10.                 price: 10,
  11.             },
  12.             {
  13.                 product: 'Memory Card',
  14.                 qty: 2,
  15.                 price: 20,
  16.             },
  17.         ];
  18.         // 计算购物车内的价格总和
  19.         let total = shoppingCart.reduce(function (previousValue, currentValue) {
  20.             return previousValue + currentValue.qty * currentValue.price;
  21.         }, 0);
  22.         console.log(total) // 550
复制代码
以上是reduce的两个比较基础的用法,你也可以把它应用在一些更复杂的场景当中。还有一个比较常见的场景就是把一个数组中相同种类的对象归为一类,形成一个新的数组。
  1. const people = [
  2.   { name: 'Kyle', age: 26 },
  3.   { name: 'John', age: 31 },
  4.   { name: 'Sally', age: 42 },
  5.   { name: 'Jill', age: 42 },
  6. ]
  7. // 把年龄相同的人分为一组
  8. const peopleGroupedByAge = people.reduce((groupedPeople, person) => {
  9.   const age = person.age
  10.   // 首先给每个存在的年龄段创建一个空数组
  11.   // 然后用push将每个元素放入相应的数组
  12.   if (groupedPeople[age] == null) groupedPeople[age] = []
  13.   groupedPeople[age].push(person)
  14.   return groupedPeople
  15.     }, {}) // 初始值是一个空对象,这样才能使用增加属性
  16.     console.log(peopleGroupedByAge)
  17. /*
  18.   {
  19.     26: [{ name: 'Kyle', age: 26 }],
  20.     31: [{ name: 'John', age: 31 }],
  21.     42: [
  22.       { name: 'Sally', age: 42 },
  23.       { name: 'Jill', age: 42 }
  24.     ]
  25.   }
  26. */
复制代码
6. every

基本语法:
  1. every((element, index, array) => { /* … */ } ) // return boolean
复制代码
  1. 最终,我们将以一个比较简单的函数收尾: every()。every方法用于检查一个数组中是否所有元素都满足条件。有<strong>任何一个不满足条件</strong>,回调函数将返回<strong>false</strong>。如果所有遍历都返回true,那么every最终将返回true
复制代码
every自身的概念很好理解,我们用一个例子来阐述他的作用
  1.         const inventors = [
  2.             { first: 'Albert', last: 'Einstein', year: 1879, passed: 1955 },
  3.             { first: 'Isaac', last: 'Newton', year: 1643, passed: 1727 },
  4.             { first: 'Galileo', last: 'Galilei', year: 1564, passed: 1642 },
  5.             { first: 'Marie', last: 'Curie', year: 1867, passed: 1934 },
  6.             { first: 'Johannes', last: 'Kepler', year: 1571, passed: 1630 },
  7.             { first: 'Nicolaus', last: 'Copernicus', year: 1473, passed: 1543 },
  8.             { first: 'Max', last: 'Planck', year: 1858, passed: 1947 },
  9.             { first: 'Katherine', last: 'Blodgett', year: 1898, passed: 1979 },
  10.             { first: 'Ada', last: 'Lovelace', year: 1815, passed: 1852 },
  11.             { first: 'Sarah E.', last: 'Goode', year: 1855, passed: 1905 },
  12.             { first: 'Lise', last: 'Meitner', year: 1878, passed: 1968 },
  13.             { first: 'Hanna', last: 'Hammarström', year: 1829, passed: 1909 }
  14.         ];
  15.         // 检查是不是所有发明家的last name都至少4个字母并且出生于1400年以后
  16.         let checkInventors = inventors.every(inventor => {
  17.             return inventor.last.length >= 4 && inventor.year>1400
  18.         })
  19.         console.log(checkInventors) // true
复制代码
最后只有一个需要额外注意的是,今天所讲的所有的数组方法,不会遍历空的数组元素
  1. console.log([1, , 3].every((x) => x !== undefined)); // true
  2. console.log([2, , 2].every((x) => x === 2)); // true
复制代码
以上就是ES6中的常见数组遍历方式,掌握他们对业务至关重要,需要在合适的情况下多多练习。
到此这篇关于JS中的常见数组遍历方法详解(forEach, map, filter, sort, reduce, every)的文章就介绍到这了,更多相关js数组遍历内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

来源:https://www.jb51.net/javascript/284555r01.htm
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

举报 回复 使用道具