Home > Web Front-end > JS Tutorial > Several commonly used traversal methods for iterable in javascript

Several commonly used traversal methods for iterable in javascript

云罗郡主
Release: 2018-10-22 16:29:25
forward
3217 people have browsed it

This article brings you some commonly used traversal methods for iterable in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

In es6, new Map and Set objects are introduced. Array can be traversed through subscripts, but Map and Set cannot be traversed through subscripts. In order to unify collections, es has introduced a new iterable type. Array, Map, and Set types all belong to iterable.

Let’s talk about several commonly used traversal methods.

1.for..in

var a = [1,2,3];for(var index in a ){
    console.log(index);    console.log(a[index]);}
Copy after login

The above outputs 0,1,2 1,2,3

Only Array can have for..in Both Map and Set It cannot be used, for..in traverses the index

2.for..of

for(var x of a){
    console.log(x);}
Copy after login
var d =  new Set(['A', 'B', 'C']);for(var dd of d){
    console.log(dd);}
Copy after login
Copy after login

for..of traverses the value

Several commonly used traversal methods for iterable in javascript

This is the result of the above operation.

The difference between for..of and for..in

for..of is a newly introduced concept in es6,

for ... inLoop Due to historical issues, what it traverses is actually the attribute names of the object. An Array array is actually an object, and the index of each element is treated as a property.

When we manually add additional attributes to the Array object, the for ... in loop will bring unexpected unexpected effects:

var a = ['A', 'B', 'C'];
a.name = 'Hello';for (var x in a) {
    console.log(x); // '0', '1', '2', 'name'
Copy after login

3.foreach() method

var d =  new Set(['A', 'B', 'C']);for(var dd of d){
    console.log(dd);}
Copy after login
Copy after login
rrree

Several commonly used traversal methods for iterable in javascript

The above is a complete introduction to several commonly used traversal methods of iterable in javascript, if you want to know more aboutJavaScript video tutorial, please pay attention to the PHP Chinese website.


The above is the detailed content of Several commonly used traversal methods for iterable in javascript. For more information, please follow other related articles on the PHP Chinese website!

source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template