ES6|数组遍历方式

ES6|数组遍历方式


ES6新增了以下三种数组遍历方法,若要与ES5对比学习,可以看看我的另外一篇博客——ES5中数组的各种遍历方法 https://blog.csdn.net/juliaandjulia/article/details/107452191.

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值