当前位置: 移动技术网 > IT编程>开发语言>JavaScript > ES6|数组遍历方式

ES6|数组遍历方式

2020年07月22日  | 移动技术网IT编程  | 我要评论

ES6|数组遍历方式


ES6新增了以下三种数组遍历方法,若要与ES5对比学习,可参考我的另外一篇博客——ES5中数组的各种遍历方法(链接: link.)

find()

array.find(function(currentValue,index,arr), thisValue)
*elem必需,表当前元素
*index可选,表当前元素索引值
*array可选,表当前元素所属的数组对象
*thisValue可选。传递给函数的值一般用 “this” 值。如果这个参数为空, “undefined” 会传递给 “this” 值

*返回满足条件的数组的第一个元素的值
*不会改变原数组
*不会对空数组进行检测

//find()
let res=arr.find(function(value){
    return value==2
})
console.log(arr,res)
console.log(arr.indexOf(res))
[1, 2, 3, 2, 4] 2
1

findIndex()

array.findIndex(function(currentValue,index,arr), thisValue)
*elem必需,表当前元素
*index可选,表当前元素索引值
*array可选,表当前元素所属的数组对象
*thisValue可选。传递给函数的值一般用 “this” 值。如果这个参数为空, “undefined” 会传递给 “this” 值

*返回数组满足条件的第一个元素位置
*不会改变原数组
*不会对空数组进行检测

//every()
let result=arr.every(function(value){
    return value==2
})
console.log(arr,result)
 [1, 2, 3, 2, 4] 1
 2

for of

场景一:
*返回数组各项的值。区别于ES5的for in——返回数组键

for(let item of arr){
    console.log(item)
}
1
2
3
2
4

场景二:
*效果等同于场景一,获取数组各项的值

for(let item of arr.values()){
    console.log(item)
}
1
2
3
2
4

场景三:
*keys() 方法用于从数组创建一个包含数组键的可迭代对象

for(let index of arr.keys()){
    console.log(index)
}
0
1
2
3
4

场景四:
*entries() 方法返回一个数组的迭代对象,该对象包含数组的键值对 (key/value)。

for(let [index,item] of arr.entries()){
    console.log(index,item)
}
0 1
1 2
2 3
3 2
4 4

本文地址:https://blog.csdn.net/juliaandjulia/article/details/107455359

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网