Table of Contents
for..of" >for..of
ES6before Code " >ES6before Code
Strings Iteration method" >Strings Iteration method
for(XYZ of ABC)" >for(XYZ of ABC)
Custom iterator" >Custom iterator
Expand knowledge: Why introduce for-of?
Home Web Front-end Front-end Q&A What are the new loops in es6?

What are the new loops in es6?

Nov 07, 2022 pm 07:29 PM
javascript es6 Loop structure Loop through

es6 has a new loop statement: "for of" loop. The "for..of" statement can loop through the entire object and is a loop of a series of values ​​produced by the iterator; the value of the "for..of" loop must be an iterable (iterable), and the syntax "for(current value of array){...}". The for-of loop not only supports arrays, but also supports most array-like objects; it also supports string traversal, and traverses strings as a series of Unicode characters.

What are the new loops in es6?

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

In the past, for loops and for in loops; and ES6 has new loops: for of loop: traverse (iterate, loop) the entire object.

for..of

ES6 adds a new for..of loop, which is generated by the iterator A loop over a series of values. for..ofThe value of the loop must be an iterable.

var a = ["a", "b","c","d","e"]
for(var idx in a){
    console.log(idx)
}
// 0 1 2 3 4
for(var val of a){
    console.log(val)
}
// a b c d e
Copy after login

for..inLoop over the keys/indexes of array a, for..ofina Loop over the value. [Related recommendations: javascript video tutorial, web front-end]

<span style="font-size: 18px;">ES6</span>before Code

var a = ["a", "b","c","d","e"]
for(var val, ret, it = a[Symbol.iterator]();(ret=it.next()) && !ret.done){
    val = ret.value
    console.log(val)
}
// a b c d e
Copy after login

At the bottom, for..of loop requests an iterator from iterable, and then repeatedly calls this iterator to assign the value it generates Give the loop an iteration variable.

JavaScriptThe standard built-in values ​​that default to iterable include:

  • Array
  • Strings
  • Generators
  • Collections/TypedArrays

Strings Iteration method

for(var c of "hello"){
    console.log(c)
}
// h e l l o
Copy after login

The native string value is cast to the equivalent String encapsulated object, which is an iterable

<span style="font-size: 18px;">for(XYZ of ABC)</span>

For XYZ, this position can be either an assignment expression or a statement. Let’s look at an example of an assignment expression:

var o = {}
for(o.a of [1,2,3]){
    console.log(o.a)
}
o // {a:3}
for({x:o.a} of [{x:1},{x:2},{x:3}]){
    console.log(o.a)
}
o // {a:3}
Copy after login

Terminates the loop early through break, continue, return.

Custom iterator

Through the understanding of the underlying layer, for..ofto iterableRequest an iterator, and then call this iterator repeatedly to assign the value it produces to the loop iteration variable. Then I can customize a iterable.

var o = {
    [Symbol.iterator](){
        return this
    },
    next(){
        if(!val){
            val = 1
        }else{
            val ++
        }
        return {value:val, done:val== 6}
    }
}
for(var val of o[Symbol.iterator]()){
    console.log(val)
}
Copy after login

It can be seen that the custom iterator satisfies two conditions, [Symbol.iterator] attribute, and the returned object has the next method, The return value of the next method must be in the form of {value:xx,done:xx}. If done:true is encountered, the loop ends.

Conclusion: The above is the entire content of the for..of loop, which can loop iterable objects.

Expand knowledge: Why introduce for-of?

To answer this question, let’s first take a look at the flaws of the three for loops before ES6:

  • forEach cannot break and return;
  • ## The shortcomings of #for-in are more obvious. It not only traverses the elements in the array, but also traverses custom properties, and even properties on the prototype chain are accessed. Also, the order in which array elements are traversed may be random.
So, in view of the above defects, we need to improve the original for loop. But ES6 won’t break the JS code you’ve written. Today, thousands of web sites rely on for-in loops, and some of them even use them for array traversal. Adding array traversal support by fixing for-in loops would make this even more confusing, so the standards committee added a new loop syntax in ES6 to solve the current problem, for-of .

So what can for-of do?

    Compared with forEach, it can respond correctly to break, continue, and return.
  • The for-of loop supports not only arrays, but also most array-like objects, such as DOM nodelist objects.
  • The for-of loop also supports string traversal, which traverses the string as a series of Unicode characters.
  • for-of also supports Map and Set (both new types in ES6) object traversal.
To summarize, the for-of loop has the following characteristics:

  • 这是最简洁、最直接的遍历数组元素的语法。
  • 这个方法避开了 for-in 循环的所有缺陷。
  • 与 forEach 不同的是,它可以正确响应 break、continue 和 return 语句。
  • 其不仅可以遍历数组,还可以遍历类数组对象和其他可迭代对象。

但需要注意的是,for-of循环不支持普通对象,但如果你想迭代一个对象的属性,你可以用
for-in 循环(这也是它的本职工作)。

最后要说的是,ES6 引进的另一个方式也能实现遍历数组的值,那就是 Iterator。上个例子:

const arr = [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;];
const iter = arr[Symbol.iterator]();
 
iter.next() // { value: &#39;a&#39;, done: false }
iter.next() // { value: &#39;b&#39;, done: false }
iter.next() // { value: &#39;c&#39;, done: false }
iter.next() // { value: undefined, done: true }
Copy after login

前面的不多说,重点描述for-of

for-of循环不仅支持数组,还支持大多数类数组对象,例如DOM NodeList对象

for-of循环也支持字符串遍历,它将字符串视为一系列的Unicode字符来进行遍历:

window.onload=function(){ 
   const arr = [55,00, 11, 22];
   arr.name = "hello";
  // Array.prototype.FatherName = &#39;FatherName&#39;;
   /*for(let key in arr){
    console.log(&#39;key=&#39;+key+&#39;,key.value=&#39;+arr[key]);
   }*/
   /* arr.forEach((data) => {console.log(data);});*/
  /* arr.forEach((data,index,arr) => {console.log(data+&#39;,&#39;+index+&#39;,&#39;+arr);});*/
  /*for(let key of arr){
    console.log(key);
  }*/
  var string1 = &#39;abcdefghijklmn&#39;;
  var string2 = &#39;opqrstuvwxyc&#39;;
  const stringArr = [string1,string2];
  for(let key of stringArr){
    console.log(key);
  }
  for(let key of string1){
    console.log(key);
  }
}
Copy after login

结果:

What are the new loops in es6?

现在,只需记住:

  • 这是最简洁、最直接的遍历数组元素的语法
  • 这个方法避开了for-in循环的所有缺陷
  • 与forEach()不同的是,它可以正确响应break、continue和return语句

for-in循环用来遍历对象属性。

for-of循环用来遍历数据—例如数组中的值。

它同样支持Map和Set对象遍历。

Map和Set对象是ES6中新增的类型。ES6中的Map和Set和java中并无太大出入。

SetMap类似,也是一组key的集合,但不存储value。由于key不能重复,所以,在Set中,没有重复的key。

要创建一个Set,需要提供一个Array作为输入,或者直接创建一个空Set

var s1 = new Set(); // 空Set
var s2 = new Set([1, 2, 3]); // 含1, 2, 3
Copy after login

What are the new loops in es6?

重复元素在Set中自动被过滤:

var s = new Set([1, 2, 3, 3, &#39;3&#39;]);
console.log(s); // Set {1, 2, 3, "3"}
Copy after login

What are the new loops in es6?

通过add(key)方法可以添加元素到Set中,可以重复添加,但不会有效果:

var s = new Set([1, 2, 3]);
s.add(4);
s; // Set {1, 2, 3, 4}
s.add(4);
s; // Set {1, 2, 3, 4}
Copy after login

通过delete(key)方法可以删除元素:

var s = new Set([1, 2, 3]);
s; // Set {1, 2, 3}
s.delete(3);
s; // Set {1, 2}
Copy after login

Set对象可以自动排除重复项

var string1 = &#39;abcdefghijklmn&#39;;
  var string2 = &#39;opqrstuvwxyc&#39;;
  var string3 = &#39;opqrstuvwxyc&#39;;
  var string4 = &#39;opqrstuvwxyz&#39;;
 
  const stringArr = [string1,string2,string3,string4];
 
 
 var newSet = new Set(stringArr);
  for(let key of newSet){
    console.log(key);
  }
Copy after login

结果:

What are the new loops in es6?

Map对象稍有不同:内含的数据由键值对组成,所以你需要使用解构(destructuring)来将键值对拆解为两个独立的变量:

for (var [key, value] of phoneBookMap) {   
console.log(key + "&#39;s phone number is: " + value);
}
Copy after login

示例

var m = new Map([[1, &#39;Michael&#39;], [2, &#39;Bob&#39;], [3, &#39;Tracy&#39;]]);
  var map = new Map([[&#39;1&#39;,&#39;Jckey&#39;],[&#39;2&#39;,&#39;Mike&#39;],[&#39;3&#39;,&#39;zhengxin&#39;]]);
  map.set(&#39;4&#39;,&#39;Adam&#39;);//添加key-value
  map.set(&#39;5&#39;,&#39;Tom&#39;);
  map.set(&#39;6&#39;,&#39;Jerry&#39;);
  console.log(map.get(&#39;6&#39;));
  map.delete(&#39;6&#39;);
   console.log(map.get(&#39;6&#39;));
  for(var [key,value] of map) {
    console.log(&#39;key=&#39;+key+&#39; , value=&#39;+value);
  }
Copy after login

结果:

What are the new loops in es6?

The above is the detailed content of What are the new loops in es6?. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles