Заявление if/else в ECMAScript
View more Tutorials:
В ECMAScript, команда if(condition) оценивает условие (condition), чтобы решить выполнить ли его блок или нет.
Ниже является структура команды if:
if (condition) { // Do something here! }
condition может быть любым значением, любым видом, или любым выражением. ECMAScript использует функцию Boolean(condition) для оценки, данная функция возвращает true или false.
Function: Boolean(condition)?
Функция Boolean(condition) возвращает false если condition имеет значение false, 0, "", null, undefined, NaN, Number.Infinite. Наоборот, данная функция возвращает true.
Изображение ниже иллюстрирует способ оценки условия ECMAScript:

Пример:
simple-if-example.js
if(true) { // Work console.log("Test 1"); } if(false) { // Not work! console.log("Test 2"); }

if-example.js
if(true) { // Work console.log("if(true)"); } if(false) { // Not work! console.log("if(false)"); } if('true') { // Work console.log("if('true')"); } if('false') { // Work console.log("if('false')"); } var obj = new Object(); if(obj) { // Work console.log("if(obj)"); } if('') { // Not work! console.log("if('')"); } if(undefined) { // Not work! console.log("if(undefined)"); } if(0) { // Not work! console.log("if(0)"); }

if-example2.js
var number0 = 0; if(number0) { // Not work! console.log("number 0 (primitive)"); } if(false) { // Not work! console.log("boolean false (primitive)"); } // A not null Object var myObj = {}; if(myObj) { // Work! console.log("A not null Object"); } // A not null Object var numberObject = new Number(0); if(numberObject) { // Work! console.log("A not null Object (Number)"); } // A not null Object var booleanObject = new Boolean(false); if(booleanObject) { // Work! console.log("A not null Object (Boolean)"); }

IfExample.java
package org.o7planning.tutorial.javabasic.controlflow; public class IfExample { public static void main(String[] args) { // Объявить переменную, представляющую ваш возраст int age = 30; System.out.println("Your age: " + age); // Условие (condition) нужное для проверки это 'age > 20' if (age > 20) { System.out.println("Okey!"); System.out.println("Age is greater than 20"); } // Код в конце блока 'if'. System.out.println("Done!"); } }
if-example3.js
// Declare a variable, representing your age let age = 30; console.log("Your age: " + age); // The condition to test is 'age> 20' if (age > 20) { console.log("Okey!"); console.log("Age is greater than 20"); } // The code blow the 'if' block. console.log("Done!");

Команда if-else так же используется для проверки условия. ECMAScript использует фукнцию Boolean(condition) для оценки условия. Если результат оценки true, блок команды if будет выполнен. Если наоборот, выполняется блок команды else.
** if - else **
if( condition ) { // Do something here } // Else else { // Do something here }

Пример:
if-else-example.js
// Declare a variable, representing your age let age = 15; console.log("Your age: " + age); // The condition to test is 'age> 18' if (age >= 18) { console.log("Okey!"); console.log("You are accepted!"); } else { console.log("Sorry!"); console.log("Age is less than 18"); } // The code after the 'if' block and 'else' block. console.log("Done!");

Структура команды if - else if - else является:
if(condition 1) { // Do something here } else if(condition 2) { // Do something here } else if(condition 3) { // Do something here } // Else else { // Do something here }

if-elseif-else-example.js
// Declaring a varible // Represent your test scores. let score = 70; console.log("Your score =" + score); // If the score is less than 50 if (score < 50) { console.log("You are not pass"); } // Else if the score more than or equal to 50 and less than 80. else if (score >= 50 && score < 80) { console.log("You are pass"); } // Remaining cases (that is greater than or equal to 80) else { console.log("You are pass, good student!"); }

Изменить значение переменной "score" в примере выше и запустить пример еще раз.
let score = 20;

Ниже является список операторов, которые обычно используются в условных выражениях (conditional expression).
- > Больше
- < Меньше
- >= Больше или равно
- <= Меньше или равно
- && и
- || или
- == Сравнить с
- != Сравнить разницу
- ! Отрицание
Пример:
if-elseif-else-example2.js
// Declare a variable, represents your age. let age = 20; // Test if age less than or equal 17 if (age <= 17) { console.log("You are 17 or younger"); } // Test age equals 18 else if (age == 18) { console.log("You are 18 year old"); } // Test if age greater than 18 and less than 40 else if (age > 18 && age < 40) { console.log("You are between 19 and 39"); } // Remaining cases (Greater than or equal to 40) else { // Nested if statements // Test age not equals 50. if (age != 50) { console.log("You are not 50 year old"); } // Negative statements if (!(age == 50)) { console.log("You are not 50 year old"); } // If age is 60 or 70 if (age == 60 || age == 70) { console.log("You are 60 or 70 year old"); } }

Вы можете изменить значение переменной 'age' и запустить пример еще раз, чтобы просмотреть результат.