您好,欢迎来到要发发知识网。
搜索
您的当前位置:首页js数组使用es6遍历方法

js数组使用es6遍历方法

来源:要发发知识网

本文教程操作环境:windows7系统、jquery3.2.1版本,DELL G3电脑。

1、forEach遍历

从头至尾遍历数组,为每个元素调用指定函数。改变数组本身。

var arr = [1, 2, 3, 4, 5, 6]
arr.forEach(function (item, idnex, array) {
    console.log(item)     // 1 2 3 4 5 6
    console.log(array)    // [1, 2, 3, 4, 5, 6]
})

2、for-of遍历 

es6新增功能,需要es6支持。

for( let i of arr){
	    console.log(i);
	}

3、find遍历

遍历数组,返回符合条件的第一个元素,如果没有符合条件的元素则返回 undefined

var arr = [1, 1, 2, 2, 3, 3, 4, 5, 6]
    
var num = arr.find(function (item, index) {
	return item === 3
})

console.log(num)   //  3

4、map遍历

调用的数组的每一个元素传递给指定的函数,并返回一个新数组。不改变原数组。函数的参数只有传进来的数组元素。

var arr = [1,2,3,4,5];
var arr1 = arr.map(function(x){
     return x*x;                     //一对一的关系,传进来一个值,返回一个对应的值。
 })      //arr1 = [1,4,9,16,25]

5、filter遍历

不会改变原始数组,返回新数组。

var arr = [
{ id: 1, text: ‘aa’, done: true },
{ id: 2, text: ‘bb’, done: false }
]
console.log(arr.filter(item => item.done))//

以上就是JavaScript数组es6新增的遍历方法,es6使用更加方便,快用起来吧~filter遍历

Copyright © 2019- net188.cn 版权所有 湘ICP备2022005869号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务