search
HomeWeb Front-endFront-end Q&AWhat are the methods to iterate arrays in es6
What are the methods to iterate arrays in es6Oct 18, 2022 pm 05:24 PM
javascriptes6es6 array

Iterative method: 1. map, used to map arrays according to certain rules to obtain a new array after mapping; 2. filter, used to filter elements based on judgment conditions; 3. forEach, equivalent to Use a for loop to traverse the array; 4. some, used to determine whether there are elements in the array that meet the conditions; 5. every, used to determine whether all elements in the array meet the conditions; 6. findIndex, used to find the element subscript; 7 , reduce, can traverse the array elements and execute a callback function for each element.

What are the methods to iterate arrays in es6

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

Array should be the most commonly used type in es6. Like arrays in other languages, it is also a set of ordered data, but the difference is that each slot of the array in the ECMAscript array can store any Type of data means that we can store strings in the first slot, values ​​in the second, and objects in the third. The most commonly used method in ECMAscript arrays is the iteration method. Let me introduce it in detail below.

7 ES6 array iteration methods

##1. map() method

Pass each item of the array into the running function and return an array composed of the results of each function call.

Function: Map the array according to a certain rule and get the new array after mapping

Application scenario:

  • (1) All elements in the array * 0.8

  • (2) Map the js objects in the array into html strings

Example:

 const arr = [10,20,30,40,50]
  // 完整写法
  // let res = arr.map((item,index)=>{
  //     return item * 0.8
  //   })
  // 熟练写法
   let res = arr.map(item=>item*0.8)
    console.log(res)
  // 返回处理后的新数组   [8, 16, 24, 32, 40]

What are the methods to iterate arrays in es6

2. filter() method

Pass each item of the array into the running function, and the item that the function returns true will Return after forming an array.

Function: Filter based on the judgment conditions.

Application scenario:

  • (1) Filter the even numbers in the array

  • (2) Filter the product price

Example:

 //需求: 筛选数组里的偶数
    const arr = [10,20,33,44,55]
    // let res =  arr.filter(item=>{
    //   if(item % 2 == 0){
    //     return true
    //   } else{
    //     return false
    //   }
    // })
    // console.log(res)
    let res1 = arr.filter(item => item % 2==0)
    console.log(res1) // [10, 20, 44]

What are the methods to iterate arrays in es6

3. forEach() method

Pass each item in the array into the running function, with no return value.

Function: equivalent to another way of writing a for loop

Application scenario: traversing an array

Example:

 // 类似for循环遍历
      const arr = [13,22,10,55,60]
      arr.forEach((item,index)=>{
        console.log(item,index)
        // item->数组里每一个元素
        // index->对应的下标
      })

What are the methods to iterate arrays in es6

4. some() method

Pass the running function to each item of the array. If one function returns true, then this method returns true.

Function: Determine whether there are elements in the array that meet the conditions (logical OR ||, any one of them can be satisfied)

Application scenarios:

  • (1) Determine whether there is an odd number in the array

  • (2) Non-empty judgment: Determine whether there is an element with an empty value in the form array

Example: Determine whether there is an odd number


 // 判断是否有奇数
    const arr = [10,20,30,40,50]
  //  let res =  arr.some(item=>{
  //     if(item % 2 == 1){
  //       return true
  //     } else{
  //       return false
  //     }
  //   })
    let res = arr.some(item =>item % 2 == 1)
    console.log(res)
   //  true: 有满足条件的元素
   //  false: 没有满足条件的元素

What are the methods to iterate arrays in es6

##5, every() methodPass the running function into each item of the array. If each item returns true, then this method is true.

Function: Determine whether all elements in the array meet the conditions (logical &&, all satisfied)

Application scenarios:

    (1) Determine whether all elements in the array are even numbers
  • (2) Switch idea: Whether to select all in the shopping cart
  • Example: Determine whether they are all even numbers

 // 判断是否全是偶数
      const arr = [10,20,30,40,50]
  //  let res =  arr.some(item=>{
  //     if(item % 2 == 1){
  //       return true
  //     } else{
  //       return false
  //     }
  //   })
    let res = arr.every(item =>item % 2 == 0)
    console.log(res)
   // true: 所有满足都满足条件
   // false: 有元素不满足条件

What are the methods to iterate arrays in es6

6. FindIndex() methodFunction:

Find the element subscript

Application scenarios:

    (1) If the array is a value type, find the element subscript Standard use: arr.indexOf(element)
  • (2) If the array is a reference type, find the element index: arr.findIndex( )
  • Example:
 /*
     arr.findIndex()查询数组下标
      如果找到目标元素,则返回改数组的下标
      如果没找到,则返回固定值-1
      */
    let arr = [
      {name:'李四',age:20},
      {name:'王五',age:20},
      {name:'张三',age:20},
    ]
 
  let index = arr.findIndex(item=>item.name == '王五')
  console.log(index)

What are the methods to iterate arrays in es6

7. reduce() methodFunction: Traverse array elements , execute the callback function once for each element

Application scenario: array sum/average/maximum value/minimum value

Example:

 const arr = [10,20,30,40,50]
   let res =  arr.reduce((sum,item,index)=>{
      return sum + item
      // console.log(sum,item,index)
    },0)

What are the methods to iterate arrays in es6

方法的区别与细节

every()和some()

这些方法中,every()和some()是最相似的,都是从数组中搜素符合某个条件的元素。对every()来说,传入的参数必须对每一项都返回true,它才会返回true。而对于some()来说,只要有一项让传入的函数返回true,它就返回true,下面举个例子:

let numbers = [2,1,4,3,5,4,3];

let everyResult = numbers.every((item,index,array) => item >2);
console.log(everyResult);  // false

let someResult = numbers.some((item,index,array) => item >2);
console.log(someResult);  // true

filter()方法

这个方法基于给定的函数来决定每一项是否应该包含在它返回的数组中。例如:

let numbers = [2,1,4,3,5,4,3];
let filterResult = numbers.filter((item,index,array) => item >2);
console.log(filterResult);  // 4,3,5,4,3

这里filter返回的数组包含了4,3,5,4,3,因为只有对这些项传入的函数才返回 true,这个方法非常适合从数组中筛选满足给定条件的元素,也是非常常用的迭代方法。

map()

map()方法也是返回一个数组。这个数组的每一项都是对原始数组中同样位置的元素运行传入函数而返回的结果,例如,可以将数组中的每一项都乘以2,并返回包含所有结果的数组,如下:

let numbers = [2,1,4,3];
let mapResult = numbers.map((item,index,array) => item *2);
console.log(mapResult);  // 4,2,8,6

这个方法返回的数组包含了原始数组中每给数值乘以2的结果。这个方法很适应于创建一个与原数组一一对应的新数组。

forEach()

最后看一看forEach这个方法,这个方法只会对每一项运行传入的函数,没有返回值。其实,本质上,forEach()方法相当于使用for循环遍历数组。例如:

let numbers = [2,1,4,3];
numbers.forEach((item,index,array) => {
console.log(item)
}); // 2,1,4,3

【相关推荐:javascript视频教程编程视频

The above is the detailed content of What are the methods to iterate arrays in es6. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
es6数组怎么去掉重复并且重新排序es6数组怎么去掉重复并且重新排序May 05, 2022 pm 07:08 PM

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

JavaScript的Symbol类型、隐藏属性及全局注册表详解JavaScript的Symbol类型、隐藏属性及全局注册表详解Jun 02, 2022 am 11:50 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

原来利用纯CSS也能实现文字轮播与图片轮播!原来利用纯CSS也能实现文字轮播与图片轮播!Jun 10, 2022 pm 01:00 PM

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

JavaScript对象的构造函数和new操作符(实例详解)JavaScript对象的构造函数和new操作符(实例详解)May 10, 2022 pm 06:16 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

JavaScript面向对象详细解析之属性描述符JavaScript面向对象详细解析之属性描述符May 27, 2022 pm 05:29 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

javascript怎么移除元素点击事件javascript怎么移除元素点击事件Apr 11, 2022 pm 04:51 PM

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

整理总结JavaScript常见的BOM操作整理总结JavaScript常见的BOM操作Jun 01, 2022 am 11:43 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

foreach是es6里的吗foreach是es6里的吗May 05, 2022 pm 05:59 PM

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!