Умовні оператори в JavaСценарій: if, else і else if
JavaУмовні оператори сценарію
Існує в основному три типи умовних операторів JavaСценарій.
- if Заява: оператор «if» виконує код на основі умови.
- if…else Заява: оператор if…else складається з двох блоків коду; коли умова істинна, виконується перший блок коду, а коли умова хибна, виконується другий блок коду.
- if… else if… else Заява: Коли потрібно перевірити кілька умов і виконати різні блоки коду залежно від того, яка з умов є істинною, використовується оператор if…else if…else.
Як використовувати умовні оператори
Умовні оператори використовуються для визначення потоку виконання на основі різних умов. Якщо умова істинна, ви можете виконати одну дію, а якщо умова хибна, ви можете виконати іншу дію.
Якщо заява
Синтаксис:
if(condition) { lines of code to be executed if condition is true }
Ви можете використовувати if
якщо ви хочете перевірити лише певну умову.
Спробуйте самі:
<html> <head> <title>IF Statments!!!</title> <script type="text/javascript"> var age = prompt("Please enter your age"); if(age>=18) document.write("You are an adult <br />"); if(age<18) document.write("You are NOT an adult <br />"); </script> </head> <body> </body> </html>
Оператор If…Else
Синтаксис:
if(condition) { lines of code to be executed if the condition is true } else { lines of code to be executed if the condition is false }
Ви можете використовувати If….Else
якщо вам потрібно перевірити дві умови та виконати інший набір кодів.
Спробуйте самі:
<html> <head> <title>If...Else Statments!!!</title> <script type="text/javascript"> // Get the current hours var hours = new Date().getHours(); if(hours<12) document.write("Good Morning!!!<br />"); else document.write("Good Afternoon!!!<br />"); </script> </head> <body> </body> </html>
If…Else If…Else оператор
Синтаксис:
if(condition1) { lines of code to be executed if condition1 is true } else if(condition2) { lines of code to be executed if condition2 is true } else { lines of code to be executed if condition1 is false and condition2 is false }
Ви можете використовувати If….Else If….Else
якщо ви хочете перевірити більше двох умов.
Спробуйте самі:
<html> <head> <script type="text/javascript"> var one = prompt("Enter the first number"); var two = prompt("Enter the second number"); one = parseInt(one); two = parseInt(two); if (one == two) document.write(one + " is equal to " + two + "."); else if (one<two) document.write(one + " is less than " + two + "."); else document.write(one + " is greater than " + two + "."); </script> </head> <body> </body> </html>