สำหรับใน
วนรอบJavaScript for in
คำสั่งวนรอบคุณสมบัติของวัตถุ:
for (key in object) {
// code block to be executed
}
const person = {fname:"John", lname:"Doe", age:25};
let text = "";
for (let x in person) {
text += person[x];
}
ลองด้วยตัวคุณเอง →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript For In Loop</h2>
<p>The for in statement loops through the properties of an object:</p>
<p id="demo"></p>
<script>
const person = {fname:"John", lname:"Doe", age:25};
let txt = "";
for (let x in person) {
txt += person[x] + " ";
}
document.getElementById("demo").innerHTML = txt;
</script>
</body>
</html>
for in วนซ้ำวัตถุ person
การวนซ้ำแต่ละครั้งจะส่งคืน คีย์ (x)
คีย์ใช้เพื่อเข้าถึง ค่า ของคีย์
ค่าของคีย์คือ person[x]
For In
โอเวอร์อาร์เรย์คำสั่ง for in
ของ JavaScript ยังสามารถวนซ้ำคุณสมบัติของอาร์เรย์ได้:
for (variable in array) {
code
}
const numbers = [45, 4, 9, 16, 25];
let txt = "";
for (let x in numbers) {
txt += numbers[x];
}
ลองด้วยตัวคุณเอง →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>For In Loops</h2>
<p>The for in statement can loops over array values:</p>
<p id="demo"></p>
<script>
const numbers = [45, 4, 9, 16, 25];
let txt = "";
for (let x in numbers) {
txt += numbers[x] + "<br>";
}
document.getElementById("demo").innerHTML = txt;
</script>
</body>
</html>
อย่าใช้ for in บน Array ถ้าดัชนี order มีความสำคัญ
ลำดับดัชนีขึ้นอยู่กับการใช้งาน และค่าอาร์เรย์อาจไม่สามารถเข้าถึงได้ตามลำดับที่คุณคาดหวัง
จะดีกว่าถ้าใช้ลูป for, for of หรือ Array.forEach() เมื่อลำดับมีความสำคัญ
Array.forEach()
forEach()
วิธีการเรียกใช้ฟังก์ชัน (ฟังก์ชันเรียกกลับ) หนึ่งครั้งสำหรับแต่ละองค์ประกอบอาร์เรย์
const numbers = [45, 4, 9, 16, 25];
let txt = "";
numbers.forEach(myFunction);
function myFunction(value, index, array) {
txt += value;
}
ลองด้วยตัวคุณเอง →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The forEach() Method</h2>
<p>Call a function once for each array element:</p>
<p id="demo"></p>
<script>
const numbers = [45, 4, 9, 16, 25];
let txt = "";
numbers.forEach(myFunction);
document.getElementById("demo").innerHTML = txt;
function myFunction(value, index, array) {
txt += value + "<br>";
}
</script>
</body>
</html>
โปรดทราบว่าฟังก์ชันรับ 3 อาร์กิวเมนต์:
มูลค่ารายการ
ดัชนีรายการ
อาร์เรย์นั้นเอง
ตัวอย่างข้างต้นใช้เฉพาะพารามิเตอร์ค่าเท่านั้น สามารถเขียนใหม่เป็น:
const numbers = [45, 4, 9, 16, 25];
let txt = "";
numbers.forEach(myFunction);
function myFunction(value) {
txt += value;
}
ลองด้วยตัวคุณเอง →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The forEach() Method</h2>
<p>Call a function once for each array element:</p>
<p id="demo"></p>
<script>
const numbers = [45, 4, 9, 16, 25];
let txt = "";
numbers.forEach(myFunction);
document.getElementById("demo").innerHTML = txt;
function myFunction(value) {
txt += value + "<br>";
}
</script>
</body>
</html>