Computer >> Máy Tính >  >> Lập trình >> Javascript

Giải thích cho. . JavaScript vòng lặp .of.


Vòng lặp for..of cho phép chúng ta lặp qua các đối tượng có thể lặp lại như mảng, chuỗi, mảng như đối tượng, danh sách nút, v.v.

Sau đây là mã cho vòng lặp for..of trong javaScript -

Ví dụ

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result,.sample {
      font-size: 20px;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>for..of loop JavaScript</h1>
<div class="sample"></div>
<div style="color: green;" class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above button to iterate over the above string using for..of loop
</h3>
<script>
   let resEle = document.querySelector(".result");
   let sampleEle = document.querySelector(".sample");
   let str = "Hello";
   sampleEle.innerHTML = str;
   document.querySelector(".Btn").addEventListener("click", () => {
      for (i of str) {
         resEle.innerHTML += i + "<br>";
      }
   });
</script>
</body>
</html>

Đầu ra

Đoạn mã trên sẽ tạo ra kết quả sau -

Giải thích cho. . JavaScript vòng lặp .of.

Khi nhấp vào nút 'BẤM VÀO ĐÂY' -

Giải thích cho. . JavaScript vòng lặp .of.