Traversal of various data structures in javascript

1.Iterator interface

Native data structures with the Iterator interface:

--Array

--Map

--Set

--String

--TypedArray (array-like object)

-- the arguments object of the function

--NodeList object

That is to say, except for the four non-traversable data types of Number, Boolean, null, and undefined, only pure Object has no Iterator interface.

Objects with the Iterator interface can be traversed with for..of  .

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

Arrays, Sets and Maps deploy these three methods. The objects generated by the three methods can only be traversed with for..of    and forEach.

Because Set has no key and only value, these four methods return the same key and value for 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 is used to traverse Array, Set, Map.

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

thisValue is the this value passed to the function.

 

3. for...in

Objects and arrays can be traversed. Cannot traverse Set and Map

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

 

5. Conventional array traversal method

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

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325104542&siteId=291194637