Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ความแตกต่างระหว่าง for...of และ for...in ใน JavaScript

ลูป for...in

ใช้วนลูปผ่าน Property ของออบเจ็กต์

ไวยากรณ์

for (variablename in object) { 
  statement or block to execute 
}

ตัวอย่าง

<html> <body> <script> 
var aProperty; 
document.write("Navigator Object Properties<br /> "); 
for (aProperty in navigator) { 
  document.write(aProperty); 
  document.write("<br />"); 
} 
document.write ("Exiting from the loop!"); 
</script> </body> </html>

ลูป for...of

ใช้วนลูปผ่านออบเจ็กต์ที่วนซ้ำได้ (Iterable) เช่น Map, Array, arguments ฯลฯ

ไวยากรณ์

for (variablename of iterable){ 
  statement or block to execute 
}

ตัวอย่าง

<!DOCTYPE html> <html> <body> <script> 
let itObj= [20, 30, 40, 50]; 
for (let res of itObj) { 
  res += 1; 
  document.write("<br>"+res); 
} 
</script> </body> </html>

ผลลัพธ์

21 31 41 51