شرح صفوف ومحتوى الفقرة
تكتب switch بهذا الشكل:
- تبدأ بكلمة switch بحروف صغيرة.
- يتبع كلمة switch الأقواس parentheses ( ).
- يتم تمرير بداخل الأقواس parentheses ( ) الأقواس expression وهو قيمة التي سوف يتم مقارنتها مع الكُتله case.
- يتبع الأقواس parentheses ( ) أقواس مُجعدة curly braces.
- يتم أضافة أي عدد من الشروط بداخل الأقواس
- يبدأ الشرط بكلمة case بحروف صغيرة.
- يتبع case قيمة هذة القيمة أما تكون متغير أو نص أو اي نوع من أنواع البيانات.
- ينتهي الشرط بعبارة break بحروف صغيرة.
إذا تطابق expression مع القيمة التي تتبع case فأن محرك جافا سكريبت سوف يقوم بتنفيذ الأمر البرمجي الموجود بداخل هذه الكُتله البرمجية بدأ من case وينتهي عند عبارة break;
وفي حالة عدم تطابق expression مع القيم الموجودة بعد كل case سوف يقوم بتنفيذ الأمر البرمجي الزي يتبع عباة default.
JavaScript Switch Syntax
طريقة كتابة Switch في لغة جافا سكريبت
switch(expression) {
case x:
/* code block - code executed when the result of expression matches x */
break;
case y:
/* code block - code executed when the result of expression matches y */
break;
default:
/* code block - code executed when the result of expression not equal or matches y */
}
body background
قم بتغيير قيمة expression بداخل switch إلي أي لون متطابق مع الحلات وفي هذة الحالة سيتم تنفيذ الأوامر الموجوده بداخل case وإذا قمت بكتابة لون غير موجود في الحلات سوف يتم تنفيذ أوامر default.
switch ("blue") {
case "red":
document.write("Color Selected is : red");
break;
case "green":
document.write("Color Selected is : green");
break;
case "blue":
document.write("Color Selected is : blue");
break;
default:
document.write("This color is not found");
}
expression as variable
يمكن تمرير expression كمتغير variable.
let expression = "red";
switch (expression) {
case "red":
document.write("Color Selected is : red");
break;
case "green":
document.write("Color Selected is : green");
break;
case "blue":
document.write("Color Selected is : blue");
break;
default:
document.write("This color is not found");
}
cases as variable
يمكن تمرير أسماء case كمتغيرات variables.
switch (expression) {
case red:
document.write("Color Selected is : red");
break;
case green:
document.write("Color Selected is : green");
break;
case blue:
document.write("Color Selected is : blue");
break;
default:
document.write("This color is not found");
}