JS ++ | Условные утверждения

Опубликовано: 10 Апреля, 2022

Условные операторы различного типа играют центральную роль в JS ++. В этом руководстве мы рассмотрим основной синтаксис и некоторые распространенные способы использования таких операторов, а также познакомимся с двумя видами выражений, которые часто используются в условных выражениях: операторы сравнения и логические операторы.

Примечание. Условные операторы JS ++, операторы сравнения и логические операторы работают аналогично их аналогам в таких языках, как JavaScript, Java, C ++ и C #.

Начнем с создания новой папки - назовите ее «Условные». Затем создайте новый файл и назовите его «Conditionals.jspp». Напишите следующий код:

 внешний $;

строка colorString;
bool LikeRed = true;
if (likeRed) {
    colorString = "красный";
}

$ ("# содержание"). текст (colorString);
$ ("# контент"). css ("цвет", colorString);

Сохраните Conditionals.jspp в папку Conditionals. Затем создайте второй файл с именем «Conditionals.html» и напишите следующее:

 <! DOCTYPE html>
<title> Программа условных операторов </title>
<body>

<p id = "content"> </p>

<script src = "http://code.jquery.com/jquery-1.12.4.min.js"> </script>
<script src = "Conditionals.jspp.js"> </script>

</body>
</html>

Сохраните Conditionals.html в папку Conditionals. Скомпилируйте Conditionals.jspp, а затем откройте Conditionals.html в браузере. Если все сработало, ваш документ должен отображаться красным шрифтом.

«Если», «еще» и «еще, если»

Conditionals.jspp shows the syntax of a simple if statement: the keyword if itself, followed by a pair of parentheses holding a condition to check, followed by a block of code in curly braces which executes if and only if the condition is true.

Примечание: фигурные скобки вокруг блока кода не обязательны, если блок содержит только один оператор. Однако для единообразия и удобочитаемости рекомендуется всегда использовать фигурные скобки.

Although if statements are often used on their own, they are also commonly used together with else statements. Let’s add an else statement to Conditionals.jspp:

external $;
    
string colorString;
bool likesRed = true;

if (likesRed) {
    colorString = "red";
}
else {
    colorString = "blue";
}
    
$("#content").text(colorString);    
$("#content").css("color", colorString);

Compile this code and then open Conditionals.html in a browser. The result is the same: the document still displays “red” in a red font. The reason is that the code in an else block only executes if the condition in the associated if statement is false. To get the code in your else block to execute, change the value of likesRed to false: Conditionals.html will then display “blue” in a blue font.

Notice that the else statement doesn’t specify a condition of its own; the only condition that is checked in Conditionals.jspp is likesRed. We simply have one block of code which executes if that condition is true, and another block which executes if it is false.

In some cases, however, we want the execution of our code to depend on more than one condition. This is where else if statements can prove useful. An else if statement supplies a condition of its own and an associated code block. The code block executes if the condition is true and all previous conditions (i.e. those associated with earlier if and else if statements) are false. Let’s revise Conditionals.jspp again to show the use of an else if statement:

external $;

string colorString;
bool likesRed = false;
bool likesBlue = true;

if (likesRed) {
    colorString = "red";
}
else if (likesBlue) {
    colorString = "blue";
}
else {
    colorString = "green";
}

$("#content").text(colorString);
$("#content").css("color", colorString);

Here the code in the else if block will execute, since its likesBlue condition is true whereas the likesRed condition specified by the earlier if statement is false. If we change the value of likesBlue to false, however, the code in the else if block will not execute, but the code in the else block will. Play around with the values of likesRed and likesBlue for yourself to see what effect they have on the conditional’s execution.

Comparison operators

Often when we use conditionals, it is because we want the execution of our code to depend on the result of a comparison of some kind. For example, suppose we want to check whether the value of a tempInCelsius variable is equal to 0, and have some code execute if it is. We would write:

if (tempInCelsius == 0) {
    // Code to be executed goes here
}

В этом условном выражении используется оператор равенства «==». Сравнение на равенство возвращает истину, если сравниваемые значения равны, и ложь в противном случае.

Примечание: оператор равенства «==» не то же самое, что оператор присваивания «=». Будьте осторожны с этим различием! Если вы случайно используете «=» вместо «==», вы внесете в свой код ошибки, которые будет трудно обнаружить.

JS++ contains various comparison operators in addition to “==”. To extend the temperature checking example, suppose we wanted to check not the exact value of tempInCelsius but rather what range it falls in. Our code might look like this:

if (tempInCelsius > 30) {
    // Code to execute if temperature is over 30
}
else if (tempInCelsius >= 15) {
    // Code to execute if temperature is between 15 and 30
}
else {
    // Code to execute if temperature is 14 or below
}

В этом примере используется оператор больше чем «>», который возвращает истину, если левый операнд больше правого операнда, и оператор больше или равно «> =», который возвращает истину, если левый операнд больше или равен к правому операнду. Здесь вы можете увидеть полный набор операторов сравнения:

Операторы сравнения в JS ++

Логические операторы

Иногда мы хотим, чтобы код выполнялся только при выполнении нескольких условий. Для этого можно использовать вложенные условные выражения, например следующие:

 внешний $;

строка colorString;
bool LikeRed = true;
bool likeBlue = true;
    
if (likeRed) {
    if (likeBlue) {
        colorString = "У меня широкий вкус к цветам";
        $ ("# содержание"). текст (colorString);
    }
}

By placing the likesBlue conditional within the likesRed conditional in this way, we ensure that the code in the likesBlue block will execute if and only if both conditions are true.

Хотя вложенные условные выражения могут использоваться для таких целей, однако они, как правило, затрудняют чтение кода, особенно когда задействованные условные выражения являются сложными. Альтернативой является использование логического оператора И «&&». Давайте заменим наше вложенное условное выражение на:

 if (likeRed &&ikesBlue) {
    colorString = "У меня широкий вкус к цветам";
    $ ("# содержание"). текст (colorString);
}

An “&&” statement takes two operands, which will normally both be Boolean expressions. Assuming they are, the statement returns true if both operands are true, and false otherwise. Thus the code above has the same effect as the earlier nested conditional: the code block executes if and only if both likesRed and likesBlue are true. The “&&” conditional is easier to read than the nested conditional, however, so is for that reason preferable.

В JS ++ помимо «&&» есть еще два логических оператора: оператор ИЛИ «||» и оператор НЕ «!». «||» является бинарным оператором типа «&&»: он принимает два операнда. Предполагая, что оба являются логическими выражениями, оператор возвращает истину, если хотя бы один операнд истинен, и ложь в противном случае. «||» полезен в тех случаях, когда вы хотите, чтобы некоторый код выполнялся, если выполняется одно или другое условие:

 if (likeRed || likeBlue) {
    colorString = "Мне нравится хотя бы один цвет";
    $ ("# содержание"). текст (colorString);
}

«!» отличается от «&&» и «||» в том смысле, что это унарный оператор: он принимает единственный операнд. Он возвращает истину, если операнд ложный, и ложь, если операнд истинный. Например:

 if (! likeRed) {
    colorString = "Не люблю красный";
    $ ("# содержание"). текст (colorString);
}

Примечание: хотя операнды управляются «&&» и «||» обычно будут логическими выражениями, это не обязательно. Чтобы охватить случаи, когда операнды не являются логическими, «&&» и «||» более точно определены следующим образом: оператор «&&» возвращает ложь, если левый операнд ложен; в противном случае он возвращает значение правого операнда. «||» оператор возвращает истину, если левый операнд истинен; в противном случае он возвращает значение правого операнда.

Операторы переключения

Sometimes you need your program to handle various different possibilities and to execute different code in each. Although you could achieve this by using a conditional with multiple else if statements, it is often simpler is to use a switch statement. A switch statement evaluates an expression and compares its value with one or more case expressions; if one of these case expressions provides a match, some associated code is executed.

Возьмем пример:

 внешний $;

строка favouriteColor;
строка colorComment;
favouriteColor = "зеленый";
    
switch (favouriteColor) {
    case "красный":
        colorComment = "красный фантастический";
        перерыв;
    case "blue":
        colorComment = "синий - это замечательно";
        перерыв;
    корпус "зеленый":
        colorComment = "зеленый - это волшебство";
        перерыв;
    case "желтый":
        colorComment = "желтый - блестящий";
        перерыв;
    дефолт:
        colorComment = "У меня нет любимого цвета";
        перерыв;
}
    
$ ("# содержание"). текст (colorComment);

In this example, the switch statement compares the value of the string favoriteColor with the various case expressions listed. When it finds a match, it executes the associated code. Since the value of favoriteColor is “green”, the switch statement executes the code associated with that case: the string colorComment is set to “green is magical“.

What is the purpose of the break and default keywords? The break keyword is very important because it’s needed if you want to prevent so-called “fallthrough”. Fallthrough happens when a switch statement executes the code associated with one or more cases after the matching case. For example, if you remove the break at the end of the green case, the switch statement will go on to set colorComment to “yellow is brilliant“. In some rare situations you may want fallthrough of this sort; if so, you would intentionally omit break. (You would also be advised to add a comment explicitly indicating that the fallthrough was intended.) Usually, however, you will want to include break at the end of each case.

The code in the default clause is executed if none of the case expressions match the original expression. The default clause is optional: if you don’t provide one, then the program resumes execution at the first statement after the switch statement.