JavaScript Statement ( Switch )

Pernyataan bersyarat digunakan untuk melakukan tindakan yang berbeda berdasarkan pada kondisi yang berbeda.
Pernyataan Beralih JavaScript

Gunakan pernyataan switch untuk memilih salah satu dari banyak blok kode yang akan dieksekusi.

Contoh :

switch(n)
{
case 1:
  execute code block 1
break;
case 2:
  execute code block 2
break;
default:
  code to be executed if n is different from case 1 and 2
}

 

Ini adalah cara kerjanya: Pertama kita memiliki ekspresi n tunggal (paling sering variabel), yang dievaluasi sekali. Nilai ekspresi tersebut kemudian dibandingkan dengan nilai-nilai untuk setiap kasus dalam struktur. Jika ada pertandingan, blok kode yang terkait dengan kasus yang dieksekusi. Gunakan break untuk mencegah kode dari berlari ke kasus berikutnya secara otomatis.

Contoh :

<script type=”text/javascript”>
//You will receive a different greeting based
//on what day it is. Note that Sunday=0,
//Monday=1, Tuesday=2, etc.

var d=new Date();
var theDay=d.getDay();
switch (theDay)
{
case 5:
document.write(“Finally Friday”);
break;
case 6:
document.write(“Super Saturday”);
break;
case 0:
document.write(“Sleepy Sunday”);
break;
default:
document.write(“I’m looking forward to this weekend!”);
}
</script>

 

This is how it works: First we have a single expression n (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically.

Leave a Reply

Your email address will not be published. Required fields are marked *