- Detalles
En este tutorial, aprenderá:
Cómo utilizar declaraciones condicionales
Las declaraciones condicionales se utilizan para determinar el flujo de ejecución en función de varias condiciones. Si una condición es verdadera, puede realizar una acción y si la condición es falsa, puede realizar otra.
Diferentes tipos de declaraciones condicionales
Hay principalmente tres tipos de declaraciones condicionales en JavaScript.
- Si una declaración
- Si … Otra declaración
- Si … Otro Si … Otro enunciado
Si una declaración
Sintaxis:
if (condition) { lines of code to be executed if condition is true }
Puede usar una declaración si solo desea verificar una condición específica.
Prueba esto por ti mismo:
<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>
Si … Otra declaración
Sintaxis:
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 }
Puede usar una instrucción If… .Else si necesita verificar dos condiciones y ejecutar un conjunto de código diferente.
Prueba esto por ti mismo:
<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>
Si … Otro Si … Otro enunciado
Sintaxis:
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 }
Puede If… .Else If… .Else enunciado si desea marcar más de dos condiciones.
Prueba esto por ti mismo:
<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>