javaScript中各种数据结构的遍历

1.Iterator接口

原生具备Iterator接口的数据结构:

--Array

--Map

--Set

--String

--TypedArray(类数组对象)

--函数的arguments对象

--NodeList对象

也就是说,除了Number, Boolean, null, undefined 四个不可遍历的数据类型,只有纯的Object没有Iterator接口。

具有Iterator接口的对象都可以用 for..of  遍历。

2.entries()、keys()、values()

数组, Set 和 Map 部署了这三种方法。三种方法生成的对象只能 for..of   和 forEach 遍历。

因为Set是没有键只有值得,因此这四个方法对于Set返回的键和值都是一样的

let arr = [1,2,3,4]
for(let key of arr.keys()){
  console.log(key)   
}
for(let value of arr.values()){
  console.log(value)
}
for(let [k,v] of arr.entries()){
  console.log(k,v)
}

forEach用于遍历数组, Set, Map。

array.forEach(function(currentValue, index, arr){}, thisValue)

thisValue是传递给函数的this值。

3. for...in

可以遍历对象和数组。不能遍历Set和Map

for(var k in obj){
  console,log(k, obj[k])
}

5.常规的数组遍历方法

for(var i=0;i < array.length; i++){
  console,log(i, array[i])   
}

猜你喜欢

转载自www.cnblogs.com/zhoulixue/p/8970108.html
今日推荐