Операторы в javascript описание и использование. Выражения и операторы. Циклические операторы языка javaScript - For

This chapter describes JavaScript"s expressions and operators, including assignment, comparison, arithmetic, bitwise, logical, string, ternary and more.

A complete and detailed list of operators and expressions is also available in the reference .

Operators

JavaScript has the following types of operators. This section describes the operators and contains information about operator precedence.

JavaScript has both binary and unary operators, and one special ternary operator, the conditional operator. A binary operator requires two operands, one before the operator and one after the operator:

operand1 operator operand2

For example, 3+4 or x*y .

A unary operator requires a single operand, either before or after the operator:

operator operand operand operator 1 / 2; // 0.5 1 / 2 == 1.0 / 2.0; // this is true

In addition to the standard arithmetic operations (+, -, * /), JavaScript provides the arithmetic operators listed in the following table:

Arithmetic operators Operator Description Example
Remainder (%) Binary operator. Returns the integer remainder of dividing the two operands. 12 % 5 returns 2.
Increment (++) Unary operator. Adds one to its operand. If used as a prefix operator (++x), returns the value of its operand after adding one; if used as a postfix operator (x++), returns the value of its operand before adding one. If x is 3, then ++x sets x to 4 and returns 4, whereas x++ returns 3 and, only then, sets x to 4.
Decrement (--) Unary operator. Subtracts one from its operand. The return value is analogous to that for the increment operator. If x is 3, then --x sets x to 2 and returns 2, whereas x-- returns 3 and, only then, sets x to 2.
Unary negation (-) Unary operator. Returns the negation of its operand. If x is 3, then -x returns -3.
Unary plus (+) Unary operator. Attempts to convert the operand to a number, if it is not already. +"3" returns 3 .
+true returns 1.
Exponentiation operator (**) Calculates the base to the exponent power, that is, base exponent 2 ** 3 returns 8 .
10 ** -1 returns 0.1 .
Bitwise operators

Use instanceof when you need to confirm the type of an object at runtime. For example, when catching exceptions, you can branch to different exception-handling code depending on the type of exception thrown.

For example, the following code uses instanceof to determine whether theDay is a Date object. Because theDay is a Date object, the statements in the if statement execute.

Var theDay = new Date(1995, 12, 17); if (theDay instanceof Date) { // statements to execute }

Operator precedence

The precedence of operators determines the order they are applied when evaluating an expression. You can override operator precedence by using parentheses.

The following table describes the precedence of operators, from highest to lowest.

Operator precedence Operator type Individual operators
member .
call / create instance () new
negation/increment ! ~ - + ++ -- typeof void delete
multiply/divide * / %
addition/subtraction + -
bitwise shift > >>>
relational < >= in instanceof
equality == != === !==
bitwise-and &
bitwise-xor ^
bitwise-or |
logical-and &&
logical-or ||
conditional ?:
assignment = += -= *= /= %= = >>>= &= ^= |=
comma ,

A more detailed version of this table, complete with links to additional details about each operator, may be found in JavaScript Reference .

Expressions

An expression is any valid unit of code that resolves to a value.

Every syntactically valid expression resolves to some value but conceptually, there are two types of expressions: with side effects (for example: those that assign value to a variable) and those that in some sense evaluate and therefore resolve to a value.

The expression x = 7 is an example of the first type. This expression uses the = operator to assign the value seven to the variable x . The expression itself evaluates to seven.

The code 3 + 4 is an example of the second expression type. This expression uses the + operator to add three and four together without assigning the result, seven, to a variable.

JavaScript has the following expression categories:

Primary expressions

Basic keywords and general expressions in JavaScript.

this

Use the this keyword to refer to the current object. In general, this refers to the calling object in a method. Use this either with the dot or the bracket notation:

This["propertyName"] this.propertyName

Suppose a function called validate validates an object"s value property, given the object and the high and low values:

Function validate(obj, lowval, hival) { if ((obj.value < lowval) || (obj.value > hival)) console.log("Invalid Value!"); }

You could call validate in each form element"s onChange event handler, using this to pass it to the form element, as in the following example:

Enter a number between 18 and 99:

Grouping operator

The grouping operator () controls the precedence of evaluation in expressions. For example, you can override multiplication and division first, then addition and subtraction to evaluate addition first.

Var a = 1; var b = 2; var c = 3; // default precedence a + b * c // 7 // evaluated by default like this a + (b * c) // 7 // now overriding precedence // addition before multiplication (a + b) * c // 9 // which is equivalent to a * c + b * c // 9

Left-hand-side expressions

Left values are the destination of an assignment.

new

You can use the new operator to create an instance of a user-defined object type or of one of the built-in object types. Use new as follows:

Var objectName = new objectType();

super

The super keyword is used to call functions on an object"s parent. It is useful with classes to call the parent constructor, for example.

Super(); // calls the parent constructor. super.functionOnParent();

Spread operator

The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.

Example: Today if you have an array and want to create a new array with the existing one being part of it, the array literal syntax is no longer sufficient and you have to fall back to imperative code, using a combination of push , splice , concat , etc. With spread syntax this becomes much more succinct:

Var parts = ["shoulders", "knees"]; var lyrics = ["head", ...parts, "and", "toes"];

Similarly, the spread operator works with function calls:

Function f(x, y, z) { } var args = ; f(...args);

var a = 10; var b = (a>1) ? 100: 200; alert(b);

Если условие a>1 истинно, то переменной b присвоить значение 100 , иначе переменной b присвоить значение 200 .

Задание Js 3_4. Дополнить код: объявлено 3 локальные переменные с использованием ключевого слова var . Необходимо в переменную max присвоить значение следующего тернарного оператора: если a больше b , то возвращаем a , иначе возвращаем b .
Фрагмент кода:

if (a * b < 6) { result = "Мало"; } else { result = "Много"; }


Вопросы для самоконтроля:

  • Каков синтаксис тернарного оператора?
  • Сколько аргументов у тернарного оператора?
  • Оператор переключения в javaScript - switch

    Оператор switch javascript служит для проверки переменной на множество значений:

    Синтаксис:

    switch (переменная или выражение) { case вариант1: //..блок операторов.. break case вариант2: //..блок операторов.. break default: //..блок операторов.. }

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

    Блок, начинающийся со служебного слова default можно опустить. Операторы блока будут выполнены в случае, если ни одно из перечисленных значений во всех case не подходит.

    Важно: Оператор break обязателен после каждого рассмотренного значения переменной (после каждого case ); если его не использовать, то будут выведены все, расположенные ниже операторы

    Сравним с оператором IF :

    var a = 2; switch(a) { case 0: // if (a === 0) case 1: // if (a === 0) alert("Ноль или один"); // тогда выводим... break; case 2: // if (a === 2) alert("Два"); // тогда выводим... break; default: // else alert("Много"); // иначе выводим... }

    Как сгруппировать несколько вариантов?

    Для выполнения одних и тех же операторов возможно группировка нескольких case . Как в примере выше:

    Case 0: case 1: alert("Ноль или один"); break; ...

    При a = 0 и a = 1 выполняется один и тот же оператор: alert("Ноль или один");

    Пример 4: Запрашивать у пользователя ввести цвет. Выводить перевод на английский язык введенного цвета. Для цвета "синий" и "голубой" выдавать одно и то же значение.


    ✍ Решение:
    • Создайте веб-страницу с html-скелетом и тегом script .
    • Инициализируйте переменную color
    • var color = prompt("Какой цвет?" ) ;

      var color = prompt("Какой цвет?");

    • Проверьте значение переменной с помощью конструкции switсh , выводя на каждое значение - соответствующий перевод:
    • switch (color) { case "красный" : alert("red"); break; case "зеленый": alert("green"); break; // ...

      Если переменная color имеет значение "красный", то вывести в модальное окно перевод - "red" и выйти из конструкции (break;). Если переменная color имеет значение "зеленый", то вывести в модальное окно перевод - "green" и выйти из конструкции (break;).

    • Для цветов "синий" и "голубой" выполните группировку:
    • // ... case "синий": case "голубой": alert("blue"); break; // ...

      Если переменная color имеет значение "синий" или переменная color имеет значение "голубой", то вывести в модальное окно перевод - "blue" и выйти из конструкции (break;).

    • Организуйте вывод для тех цветов, которые не предусмотрены программой:
    • // ... default : alert("y нас нет сведений по данному цвету" ) } // конец switch

      // ... default: alert("y нас нет сведений по данному цвету") } // конец switch

    • Протестируйте сценарий в браузере.

    Задание Js 3_6. Найдите и исправьте ошибки в следующем фрагменте кода:

    14 15 16 17 var number = prompt("Введите число 1 или 2:" ) ; switch (number) { case "1" { document.write ("Один" ) ; } ; break ; case "2" { document.write ("Два" ) ; } ; break ; default { document.write ("Вы ввели значение, отличное от 1 и 2" ) ; } ; }

    var number = prompt("Введите число 1 или 2:"); switch (number) { case "1" { document.write("Один"); }; break; case "2" { document.write("Два"); }; break; default { document.write("Вы ввели значение, отличное от 1 и 2"); }; }


    Задание Js 3_7. Что выведется на экране при выполнении следующего кода?:

    1 2 3 4 5 6 7 8 9 10 11 12 13 var value = "2" ; switch (value) { case "1" : case "2" : case "3" : document.write ("Hello" ) ; break ; case "4" : case "5" : document.write ("World" ) ; default : document.write ("Error" ) ; }

    var value = "2"; switch (value) { case "1": case "2": case "3": document.write("Hello"); break; case "4": case "5": document.write("World"); default: document.write("Error"); }


    Задание Js 3_8. У пользователя запрашивать число – количество ворон на ветке. В зависимости от введенного числа (не более 10), выводить сообщение: - На ветке сидит 1 ворона - На ветке сидит 4 вороны - На ветке сидит 10 ворон

  • В зависимости от введенного числа, меняется окончание у слова "ворона" .
  • Для проверки использовать оператор Switch javascript.
  • Сохраните данную страницу в папке результатов (она пригодится для дальнейших работ).

  • Вопросы для самоконтроля:

  • В каком случае целесообразно в качестве условного оператора использовать конструкцию switch ?
  • Для чего служит блок default в операторе switch ?
  • Обязательно ли использование оператора break в конструкции switch ?
  • Как осуществляется группировка для нескольких вариантов значений в операторе switch ?
  • Циклические операторы языка javaScript - For

    Синтаксис:

    for(начальное значение счетчика; условие; приращение счетчика) { //..блок операторов.. }

    Важно: Цикл в javascript for используется, когда заранее известно, сколько раз должны повториться циклические действия (сколько итераций у цикла)

    • В качестве начального значения счетчика итераций используется выражение присваивания: например, i=0 - счетчик цикла начинается с нуля:
    • for(var i = 0; условие; приращение счетчика) { //..блок операторов.. }

    • В качестве приращения счетчика указывается шаг, с которым должен увеличиваться счетчик: например, указывает на то, что каждая итерация цикла будет сопровождаться его увеличением на 1 :
    • for(var i = 0; условие; i++) { //..блок операторов.. }

    • Условие цикла - это и есть конечное значение счетчика: например, i10, останавливает цикл:
    • for(var i = 0; i