JavaScript สำหรับของ


สารบัญ

    แสดงสารบัญ


for of วนซ้ำ

คำสั่ง JavaScript for of วนซ้ำ ผ่านค่าของวัตถุที่สามารถทำซ้ำได้

ช่วยให้คุณสามารถวนซ้ำโครงสร้างข้อมูลที่สามารถทำซ้ำได้ เช่น Arrays, Strings, Maps, NodeLists และอื่นๆ:

ไวยากรณ์

for (variable of iterable) {
  // code block to be executed
}

ตัวแปร - สำหรับการวนซ้ำทุกครั้ง ค่าของคุณสมบัติถัดไปจะเป็น กำหนดให้กับตัวแปร ตัวแปร สามารถประกาศได้ด้วย const, ให้ หรือ var

iterable - ออบเจ็กต์ที่มีคุณสมบัติที่สามารถทำซ้ำได้


รองรับเบราว์เซอร์

For/of ถูกเพิ่มลงใน JavaScript ในปี 2015 (ES6)

Safari 7 เป็นเบราว์เซอร์ตัวแรกที่รองรับ:

Chrome 38 Edge 12 Firefox 51 Safari 7 Opera 25
Oct 2014 Jul 2015 Oct 2016 Oct 2013 Oct 2014

สำหรับ/ของ ไม่ได้รับการสนับสนุนใน Internet Explorer


การวนซ้ำบนอาร์เรย์

ตัวอย่าง

const cars = ["BMW", "Volvo", "Mini"];

let text = "";
for (let x of cars) {
  text += x;
}

ลองด้วยตัวคุณเอง →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript For Of Loop</h2>
<p>The for of statement loops through the values of any iterable object:</p>

<p id="demo"></p>

<script>
const cars = ["BMW", "Volvo", "Mini"];

let text = "";
for (let x of cars) {
  text += x + "<br>";
}

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

วนซ้ำบนสตริง

ตัวอย่าง

let language = "JavaScript";

let text = "";
for (let x of language) {
  text += x;
}

ลองด้วยตัวคุณเอง →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript For Of Loop</h2>

<p>The for of statement loops through the values of an iterable object.</p>

<p id="demo"></p>

<script>
let language = "JavaScript";

let text = "";
for (let x of language) {
  text += x + "<br>";
}

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

ในขณะที่ห่วง

ลูป While และลูป do/ While จะอธิบายไว้ในบทถัดไป