ES系列 | ES6数组遍历方式

621 阅读2分钟

「这是我参与2022首次更文挑战的第6天,活动详情查看:2022首次更文挑战」。

ES系列文章

ES6 数组遍历方式

  • find()
  • findIndex()
  • for of :values() | keys() | entries()

find():返回第一个通过测试的元素

array.find(function()){}

  • 返回满足条件数组的第一个元素的值
  • 不会改变原数组
  • 不会对空数组进行检测
let arr= [1, 2, 3, 2, 4];
let res=arr.find(function(value){
return value==2 
})
console.log(arr,res) 
//[1, 2, 3, 2, 4] 2
console.log(arr.indexOf(res))

findIndex():返回的值为该通过第一个元素的索引

array.findIndex(function()){}

  • 返回数组满足条件的第一个元素位置
  • 不会改变原数组
  • 不会对空数组进行检测
let arr= [1, 2, 3, 2, 4];
let result=arr.findIndex(function(value){ 
    return value==2 
}) 
console.log(arr,result)
//[1, 2, 3, 2, 4] 1

for of

  1. 场景一:
  • 返回定义数组中各项的值。区别于ES5的for in——返回数组键
let arr= [1, 2, 3, 2, 4];
for(let item of arr){
    console.log(item)
}
//1 2 3 2 4
  1. 场景二: values()
  • 效果等同于场景一,都是获取数组各项的值
let arr= [1, 2, 3, 2, 4];
for(let item of arr.values()){
    console.log(item)
}
//1 2 3 2 4
  1. 场景三:keys()
  • keys() 方法用于数组创建一个包含数组键的下标或索引
let arr= [1, 2, 3, 2, 4];
for(let index of arr.keys()){
    console.log(index)
}
// 0 1 2 3 4
  1. 场景四:entries()
  • entries() 方法返回一个数组的迭代对象,该对象包含数组的键值对 (key/value)索引和下标。
let arr= [1, 2, 3, 2, 4];
for(let [index,item] of arr.entries()){
    console.log(index,item)
}
//0 1 2 3 4索引
//1 2 3 2 4值

总结

通过ES5和ES6中的数组遍历方式,发现每一种数组遍历方式各自有各自特点,要学会在不同的场景灵活使用不同的遍历方式去循环遍历数组。

一个前端小白,若文章有错误内容,欢迎大佬指点讨论!