
本文教程操作环境:windows7系统、jquery3.2.1版本,DELL G3电脑。
1、forEach遍历
从头至尾遍历数组,为每个元素调用指定函数。改变数组本身。
1 2 3 4 5 | var arr = [1, 2, 3, 4, 5, 6]
arr.forEach( function (item, idnex, array ) {
console.log(item)
console.log( array )
})
|
2、for-of遍历
es6新增功能,需要es6支持。
1 2 3 | for ( let i of arr){
console.log(i);
}
|
3、find遍历
遍历数组,返回符合条件的第一个元素,如果没有符合条件的元素则返回 undefined
1 2 3 4 5 6 7 | var arr = [1, 1, 2, 2, 3, 3, 4, 5, 6]
var num = arr.find( function (item, index) {
return item === 3
})
console.log(num)
|
4、map遍历
调用的数组的每一个元素传递给指定的函数,并返回一个新数组。不改变原数组。函数的参数只有传进来的数组元素。
1 2 3 4 | var arr = [1,2,3,4,5];
var arr1 = arr.map( function (x){
return x*x;
})
|
5、filter遍历
不会改变原始数组,返回新数组。
1 2 3 4 5 | 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遍历