JavaScript operators

Time:2021-10-17

##1. Operator

1.1. Arithmetic operator

operator describe example result
+ addition var num = 1 + 2; 3
subtraction var num = 4 – 3; 1
* multiplication var num = 4 * 3; 12
/ division var num = 6 / 3; 2
% Surplus var num = 7 % 3; 1
  • Normal data operation
//Use + between strings to spell strings - * / No
//During data operation, other operators except '+' can automatically convert string numbers into numbers
var num1 = '8';
var num2 = 4;

console.log(num1 + num2); // 84 // String splicing
//The following are normal operations
console.log(num1 - num2); //4
console.log(num1 / num2); //2
console.log(num1 * num2); //32
console.log(num1 % num2); // 0 // residual
  • During data operation, other operators except ‘+’ can automatically convert string numbers into numbers
var num1 = '8';
var num2 = '4';

console.log(num1 - num2); //4
console.log(num1 / num2); //2
console.log(num1 * num2); //32
console.log(num1 % num2); //0

1.2. Unary operator

There are eight common unary operators in JavaScript
operator describe
+ Convert operands to numbers, string splicing
Converts an operand to a number and becomes negative
! Logical negation operator
++ Increasing
Diminishing
delete Deletes the value of a specific index in an array or object
typeof When the operand is placed after typeof, it will return the type of the current operand. For numeric types, it can be returned accurately. For reference types, function will return ‘function’, and others will only return ‘object’
void The void operator returns undefined for any value.

+(plus sign)

1. The first use of ‘+’ is to add data
var num1 = 3;
var num2 = 5;
var sum = num1 + num2; //8
2. ‘+’ placed in front of the data is a positive number
var num = 6;
console.log(+num); // 6
3. ‘+’ is a string connector when it operates with a string
//'+' is a string connector when it operates with a string
var a = 'hello';
var b = 'world';
var c = 6;
console.log(a + b); // helloworld
//Strings and strings, numbers and strings, using '+' is the splicing of strings
console.log(a + b + c);  //helloworld6
4. ‘+’ can implicitly convert numeric string or boolean type to number type
//'+' can implicitly convert numeric strings or Boolean types to number types
var a = '123';
var b = true;
//Implicit conversion
console.log(+a, +b); // 123  1

-(minus sign)

1. Positive and negative signs can take positive or negative numbers, and other operators cannot be converted
var num1 = 6;
var num2 = -6;
console.log(-num1); //-6
console.log(+num1); //6
console.log(-num2); //6
console.log(+num2); //-6
2. Positive and negative signs can implicitly convert string numbers to numbers
var num1 = '20';
var num2 = '-20';
console.log(-num1); //-20
console.log(+num1, typeof +num1); //20 number
console.log(-num2); //20
console.log(+num2, typeof +num2); //-20 number

! (reverse)

It is often used as negation operation and type judgment in condition judgment. You can also use ‘!’ Convert variable to boolean type
//It is often used as negation operation and type judgment in condition judgment. You can also use '!' Convert variable to boolean type

var a;
If (a) {// because a is undefined, it defaults to false. If false, the first one is output 
     Console. Log ('a is false ');
}else{
     Console.log ('a is true ');
}

var b = 111;   // Because B is assigned, it defaults to true
if (b) {  
     Console. Log ('b is true ')// B is true
}else{
     Console. Log ('b is false ');
}



var c = 111;   // Because C is assigned, it defaults to true
If (! C) {// C is false after negation
     Console.log ('! C is false');
}else{
     Console.log ('! C is true');
}


console.log(!null);  //true
console.log(!undefined);  //true
console.log(!''); //true
console.log(!100);  //false
console.log(!'abc');  //false

++(incremental)

It is usually used for loop statements, animation operations, etc.

++Put it in front and assign value: accumulate first and then assign value
//Increasing
//+ + is placed in front and assigned: accumulate 1 first and then assign a value
var num = 1;
var a = ++num;   //a = 2
Console.log ("num first adds 1 and then assigns a value to a"// two
Console.log ("+ + num" + Num)// two
//Num first adds 1 to itself and then assigns a value to a
++Put it later and assign value: assign value first and then accumulate
var num = 0;
var a = num++;
console.log(a); // 0
console.log(num); // 1
//First assign the value of num to a, and then add 1 to num

–(decreasing)

It is usually used for loop statements, animation operations, etc. The use method is similar to that of + +.

delete

Deletes the value of a specific index in an array or object
//Delete delete object
var obj = {
  name:'zhangsan',
  age: 17
};
delete obj.name;   // Delete point syntax directly through attribute name
console.log(obj); // {age: 17}

//Delete array
var arr = [1,2,3,4,5];
//Delete by subscript index
delete arr[2];
//Delete array中的元素后,数组仍会保留该元素的内存空间
console.log(arr); //[ 1, 2, <1 empty item>, 4, 5 ]

typeof

When the operand is placed after typeof, it will return the type of the current operand. For numeric types, it can be returned accurately. For reference types, function will return ‘function’, and others will only return ‘object’

var obj = {
  name:'zhangsan',
  age: 17
};
var arr = [1,2,3,4,5];
console.log(typeof obj, typeof arr); //object object

void

Discards the return value of the expression and returns undefined
There are two ways to use void expression and void (expression)

Extensions: Javascript implicit conversion

  • There are two types of data types in javascript: original type and object type:

Original type (base type):

Undefined, null, string, number, Boolean, symbol (ES6 new, not considered temporarily)

object type

object

  • Since implicit conversion is required, there should be a set of conversion rules to track what is finally converted

Implicit conversion mainly involves three types of conversion:

1. Convert the value to the original value, toprimitive().

2. Convert the value to a number, tonumber().

3. Convert the value to a string, tostring().

  • Convert the value to the original value through toprimitive

The abstract operation toprimitive inside the JS engine has such a signature:

ToPrimitive(input, PreferredType?)

Input is the value to be converted, preferredtype is an optional parameter, and can only be of type number or string.
It is just a conversion flag. The converted result is not necessarily the type of the parameter value, but the conversion result must be an original value (or an error).

It is special to calculate the original value of date. Preferredtype is string and other object objects are number.

  • Conversion of basic types

add , subtract , multiply and divide:

1. Add a number to a string, and the number will be converted into a string. No conversion is required for numbers plus numbers or strings plus strings.

In the process of addition, first, the left and right sides of the equal sign are subjected to the original value toprimitive() operation, and then if there are two or more original values, as long as one of them is of string type, the two or more original values are converted to string tostring() operation for character string splicing; Otherwise, two or more original values are converted to digital tonumber() operation for digital addition.

var a = 1 + 2 + '3';
console.log(a, typeof a); // '33'    string
var b = 1 + 2 + 3;
console.log(b, typeof b); // 6   number

2. The number subtracts the string, and the string is converted to a number. If the string is not a pure number, it will be converted to Nan. The same is true for strings minus numbers. The subtraction of two strings is also converted to a number first.

console.log(10 - '20'); //-10
console.log(10 - 'one');  //NaN
console.log(10 - '100a'); //NaN

3. The same is true for the conversion of multiplication, division, greater than, less than and subtraction.

//The implicit conversion of multiplication and division is converted to number type by default
 console.log(10 * '20');      //200
 console.log('10' * '20');    //200

console.log(30/'20');      //2
console.log('20'/'10');   //2
console.log('20'/'one');   //NaN
  • Implicit conversion for = =

1. Undefined equals null

2. When comparing a string with a number, the string is converted to a number

3. When comparing numbers with Booleans, Booleans turn to numbers

4. When comparing string and Boolean, they are converted to numbers

// ==
console.log(undefined == null); //true
console.log('0' == 0);// True, string to number
console.log(0 == false);// True, Boolean to number
console.log('0' == false); // true, convert both to numbers
  • Conversion of reference types

    The comparison between basic types is relatively simple. The comparison between reference type and basic type is relatively complex. First, convert the reference type into basic type, and then compare according to the above method.

Preferredtype conversion policy
  • If the preferredtype is marked as number, the following operation process will be carried out to convert the entered value.

1. If the entered value is already an original value, it is returned directly

2. Otherwise, if the entered value is an object, the valueof () method of the object is called,
If the return value of the valueof () method is an original value, the original value is returned.

3. Otherwise, the toString () method of the object is called. If the toString () method returns an original value, the original value is returned.

4. Otherwise, a typeerror exception is thrown.

//Object implicitly converts the default preferredtype -- > number
//Convert object to basic data type string type 
var obj={
     name:'lisi',
     age:12,
      
}
//If the value entered is an object, the valueof () method of that object is called
console.log(obj.valueOf().toString(),typeof obj.valueOf().toString()); // [object] string // implicit conversion
//When an object and a string are added, the object must be converted to the basic data type before the operation
console.log(obj + 'a');// [object] A // convert the object to the reference data type before concatenating
  • If preferredtype is marked as string, the following operation process will be carried out to convert the entered value.

1. If the entered value is already an original value, it is returned directly
2. Otherwise, the toString () method of the object is called. If the toString () method returns an original value, the original value is returned.
3. Otherwise, if the entered value is an object, the valueof () method of the object is called,
If the return value of the valueof () method is an original value, the original value is returned.
4. Otherwise, a typeerror exception is thrown.

be careful:

The value of preferredtype will be automatically set according to the following rules:

1. If the object is of date type, the preferredtype is set to string

2. Otherwise, the preferredtype is set to number

case
[] + [] // ""


console.log([].valueOf().toString(),typeof([1,2,3,4].valueOf().toString()));   // string
console.log([1,2,3]+[2,3,4]); // 1,2,32,3,4 // the array becomes a string and then concatenated

For toprimitive, both are array objects, not date objects. Therefore, number is taken as the conversion standard, so valueof() is called first, and the result is [], which is not the original value. Therefore, continue to call tostring(), and the result is the original value of “” (empty string), and return “”. The second [] procedure is the same and returns’ ‘. The results on both sides of the plus sign are of string type, so string splicing results in ”.

[] + {}    // "[object Object]"


var obj = {
     name:'zhang',
     age:16
}
console.log([1,2,3].valueOf().toString(),typeof [1,2,3].valueOf().toString()); //1,2,3 string

console.log(obj.valueOf().toString(),typeof obj.valueOf().toString());  //[object Object] string
 
console.log([1,2,3] + obj);  //123[object Object]
//Proof [] implicitly converted to empty string ''
console.log([] + obj);  //""[object Object]

For toprimitive, number is still used as the conversion standard.
The result of [] is’ ‘.
{} call valueof() first, and the result is {}, which is not the original value. Therefore, continue to call tostring(), and the result is “[object]” which is the original value. Return “[object]”.
The results on both sides of the plus sign are of string type, so string splicing will result in “[object]”.

{} + [] // 0 // to be analyzed separately

{} + [] is equivalent to {}+ [] ---- > > empty code block + empty string ----- > > + empty string ----- > > the positive value of empty string is 0

 //This cannot be seen from the output results
console.log({}.valueOf().toString(),{}.valueOf().toString());  //[object Object] [object Object] 
//Vscode output results
console.log({} + []);  //[object Object]

This question follows the steps of the previous question. If it is reasonable, the result should still be “[object]”, but the result is unexpected – the displayed answer is 0!
What is the reason? The original {} + [] is parsed into {}+ [] is preceded by an empty code block, which is skipped, and the remaining + [] becomes a unary operation. The original value of [] is’ ‘, and the result of converting’ ‘to number is 0.

{} + {} // "[object Object][object Object]"

//In node, the statements that start with "{" and end with "}" will be wrapped with a layer (), which will become ({} + {}), and the results meet the expectations
console.log({} + {});  //[object Object][object Object]

In the Canary version of Chrome browser and node, the results are as expected.
The result is “object object”.
In the normal version of Chrome browser, the result is Nan.
Why? The reason is that in the node, the statements starting with “{” and ending with “}” will be wrapped with a layer (), which will become ({} + {}), and the results meet the expectations. The normal version of chrome will still parse into {}+ {}, the result becomes Nan

1.3. Assignment operator

operator example Equivalent to
= x = y x = y
+= x += y x = x + y
-= x -= y x = x – y
*= x *= y x = x * y
/= x /= y x = x / y
%= x %= y x = x % y

=The assignment operator assigns a value to a variable.

//= the assignment operator assigns a value to a variable.
var x = 7;
console.log(x);  //7

+=Assignment operators add values to variables.

//Addition operation
var x = 7;
x += 8; 
console.log(x);  //15

-=The assignment operator subtracts a value from a variable.

//Subtraction operation
var x = 7;
x -= 8; 
console.log(x);  //-1

*=The assignment operator multiplies the variable.

//Multiplication
var x = 7;
x *= 9; 
console.log(x);  //63

/=The assignment operator divides the variable.

//Division operation
var b = 7;
b /= 8; 
console.log(b);  //0.875

%=The assignment operator assigns the remainder to a variable.

//Surplus
var c = 7;
c %= 8; 
console.log(c); //7

1.4. Comparison operator

Comparison operators are used in logical statements to determine whether variables or values are equal. It is usually used in conditional judgment statements.

The priority of comparison operators is lower than that of arithmetic operators and higher than that of assignment operators. Generally, the operation result is Boolean

operator describe compare return
== be equal to x == 8 false
x == 5 true
x == “5” true
=== Equal values and types x === 5 true
x === “5” false
!= Unequal x != 8 true
!== Unequal values or types x !== 5 false
x !== “5” true
x !== 8 true
> greater than x > 8 false
< less than x < 8 true
>= Greater than or equal to x >= 8 false
<= Less than or equal to x <= 8 true

==

Equivalence means that when the value types on both sides are different, you should first convert the type to the same type, and then compare whether the values are equal.

//Commonly used for comparison of values of the same type
console.log(123 == 345);  //false
console.log('123' == '345');  //false

//If the two value types are different, they may also be equal. Type conversion shall be carried out according to the following rules
//If one is null and the other is undefined, then it is equal
console.log(null == undefined); //true

//If one is a string and the other is a numeric value, convert the string into a numeric value and compare it
console.log(123 == '123');  //true

//If the numeric values of integer type and boolean type are compared, 1 and true use = = and the comparison result is true,
//0 and false use = = the comparison result is also true, and others are false; It can be understood that when = = is used to compare integers, 1 is equal to true and 0 is equal to false.
console.log(1 == true); //true
console.log(0 == false);  //true

===

Identity means that without type conversion, the results of different types must be different.

//If the types are different, they must not be equal
console.log(123 === '123'); //false

//If both are numerical values and are the same value, they are equal; If at least one of them is Nan, it is not equal. (to judge whether a value is Nan, you can only use isnan())
console.log(123 === 123); //true
console.log(123 === 10 / 'a');  //false

//If both are strings and the characters in each position are the same, they are equal, otherwise they are not equal.
console.log('hello' === 'hello'); //true

//If both values are true or false, they are equal
console.log(true === true); //true
console.log(1 === true);  //false

//If both values are null or undefined, they are equal
console.log(null === null); //true
console.log(null === undefined);  //false
The difference between double and third class

Double class means that it can be true as long as the values are equal, while third class requires not only equal values, but also the same type.
Suggestion: try to use strict operator class III. Because “= =” is not rigorous, it may bring some counterintuitive consequences.

be careful

1. For basic types such as string and number, there are differences between double and third

1) For comparison between different types, double level comparison is used to “convert the value into the same type” to see whether the “values” are equal, = = = if the types are different, the results are unequal

2) For the same type comparison, the “value” comparison is performed directly, and the results are the same

2. For advanced types such as array and object, there is no difference between double and third

Make a pointer address comparison

3. There are differences between basic type and advanced type, double grade and third grade

1) For = =, convert advanced to base type for value comparison

2) Because of different types, = = = the result is false

!=

!= The usage is similar to = =. If the types are different, first try to convert the types, then compare the values, and finally return the value comparison results.

!==

!== Similar to = = = usage, its values are compared only under the same type.

‘>’ and ‘<‘ are greater than and less than

var a = 10;
var b = 20;
console.log(a > b); //false
console.log(a < b); //true

‘> =’ and ‘< =’ greater than or equal to and less than or equal to

var a = 10;
var b = 20;
console.log(a >= b); //false
console.log(a <= b); //true

Use ‘>’ ‘<‘ ‘=’ ‘< =’ ‘in case of non numeric value

When comparing non numeric values, they are converted to numeric values before comparison.
//True to numeric value is 1, false to numeric value is 0
console.log(1 > true); //  The result is false
console.log(1 >= true); //  The result is true
console.log(1 > '0'); //  The result is true
console.log(1 > null); //  The result is true

//Any value compared with Nan is false
console.log(1 > 'hello'); //  The result is false. Any value compared with Nan is false

If both sides of the symbol are strings, they will not be converted to numerical values for comparison, but the Unicode encoding of the characters in the string will be compared respectively.
Note: therefore, when comparing two string numbers, be sure to transform first.

console.log('134545353' > '5'); //  False if no transformation
console.log('134545353' > +'5');//  Only in this way will the result return true

When comparing character codes, they are compared bit by bit. If the first bit on both sides of the symbol is the same, the next bit is comparedTherefore, it can be used to sort English, but it is meaningless to compare Chinese.

console.log('1' < '5'); //  The result is true
console.log('11' < '5'); //  The result is also true
console.log('be' > 'b'); //  The result is true. First compare the character codes of the first bit B, and then compare the second bit. Because be has e and B has only one bit, be > B
console.log('be' < 'b'); //  The result is false

1.5. Logical operators

operator describe example
&& and (x < 10 & & Y > 1) is true
OR operator or
! not ! (x = = y) is true

&&And (true is true, false is false)

Can be applied to any value. If an operand is not Boolean, logical and does not necessarily return Boolean

If the first operand is null, Nan, undefined, false, 0, “” can be converted to a value of false

console.log(null && 'world'); //null

When the first expression is true, the result of the whole expression depends on the second expression, and the second expression is returned

console.log('hello' && 'world'); //world

When the first expression is false, the result of the whole expression can be determined and the first expression is returned

console.log(false && 'world'); //false

[null, Nan, undefined, false, 0, “”] returns the operand directly

console.log(''&&123);  //''   Empty string
console.log(0&&null);  //0
console.log(123&&345); //345
console.log(123&&undefined); //undefined

||(if there is real talent, it is true, and if there is the same false, it is false)

If two or more operands are null, Nan, undefined, false, 0, “” can be converted to a value of false.

console.log(null || false); //false

If the first operand is null, Nan, undefined, false, 0, “”, the second operand is returned.

console.log(null || 'hello'); //'hello'

If the first operand is true, the first operand is returned directly.

console.log(123||345);   //123

When the first expression is true, the result of the whole expression can be determined and the first expression is returned

When the first expression is false, the result of the whole expression depends on the second expression, and the second expression is returned

If one is true, the result is true

If it is also false, the result will be false

!(NOT)

It is often used as negation operation and type judgment in condition judgment. You can also use ‘!’ Convert variable to boolean type

var a;
if (!a) {}
console.log(!null);  //true
console.log(!undefined);  //true
console.log(!''); //true
console.log(!100);  //false
console.log(!'abc');  //false

1.6. Ternary operator

When the ternary operator in JavaScript is used as a judgment

The basic syntax is: expression? sentence1 : sentence2
When the value of expression is true, execute sentince1, otherwise execute sentince2
var age = 19;
var result = age > 16 ?  "Adult": "minor";
//When age is greater than 16 years old, the condition is true, and sentence1 is executed, followed by vice versa

2. Type conversion

2.1. * = > string type

Convert other types to string

Tostring() function

In addition to null and undefined, variables of the other three basic data types have a tostring() function, which can obtain the string representation of the specified value of the variable.

var a = true;
var b = 123;
console.log(a.toString(), b.toString());// 'true'  '123'
console.log(typeof a.toString(), typeof b.toString());//string string

If the variable is of number type, by default tostring() is a string representation of the returned value in decimal format. By passing parameters, you can enter string values in binary, octal, hexadecimal or even any valid hexadecimal format

var num = 10;
console.log(num.toString());  //"10"
console.log(num.toString(2))    //"1010"
console.log(num.toString(8))    //"12"
console.log(num.toString(16))    //"a"

Any other data added to the string is converted to a string

console.log(typeof (true + ''));  //string

2.2. * = > boolean type

Other data types are converted to Boolean

Boolean() wrapper

Boolean('hello') //true

use!! Any other data type can be converted to a boolean type.

!!'hello' //true

2.3. * = > number type

Other data types are converted to number

Number() wrapper

If the converted value is null, undefined, Boolean, number

Number(true); //1
Number(false); //0
Number(null); //0
Number(undefined); //NaN
Number(10); // 10 if it is a digital value, output as is

If the converted value is string

Number("123"); // 123if only numeric values are included, convert to the corresponding numeric value
Number("234.1"); // 234.1 resolve to corresponding decimal 
Number("+12.1"); // 12.1 the first is the sign bit, the rest is the value, which is converted to the corresponding value 
Number("1+2.3"); //  The Nan sign bit appears in other locations and resolves to Nan 
Number("0xa"); // 10 if only hexadecimal format is included, it is converted to the corresponding decimal value
Number("010"); // 10 [note] will not be parsed as octal, and the result is 10. 
Number(""); //  0 an empty string is converted to 0 
Number("123ac"); //  Nan contains other characters: Nan 
Number(12); //12
Parseint() function

If the converted values are null, undefined and Boolean, they are all converted to Nan

If the converted value is number

parseInt(10); // 10 if it is an integer value, output parseInt (10.3) as is// 10 if it is a decimal point, the content after the first decimal point shall be rounded off

If the converted value is string

parseInt("123"); // 123; If only numeric values are included, convert to the corresponding numeric value
parseInt("234.1"); // 234; Values after the decimal point are omitted 
parseInt("+12.1"); // 12;  The first bit is a sign bit, the rest is a numeric value, which is converted to an integer 
parseInt("1+2.7"); // 1;  If the sign bit appears in another position, the value before the sign bit is retained 
parseInt("0xa"); // 10;  If it contains only hexadecimal format, it is converted to the corresponding decimal value
parseInt("010"); // 10;  [note] it will not be parsed as octal, and the result is 10
parseInt(""); // NaN; The empty string is converted to Nan
parseInt("1+2.3"); // 1; If the first value is a numerical value, analyze backward in turn to find a continuous numerical value until the first non numerical value is encountered, convert the previously obtained numerical value into number and return parseInt ("123ac")// 123;
Parsefloat() function

If the converted values are null, undefined and Boolean, they are all converted to Nan

If the converted value is number

parseFloat(10); // 10 if it is an integer value, output parsefloat (10.1) as is// 10.1 if it is decimal, keep the decimal point, but if it is 10.0, the result is 10

If the converted value is string

parseFloat("123"); // 123; If only numeric values are included, convert to the corresponding numeric value
parseFloat("234.1"); // 234.1; Keep the value after the decimal point 
parseFloat("+12.1"); // 12.1;  The first bit is a sign bit, the rest is a numeric value, which is converted to an integer 
parseFloat("1+2.6"); // 1; If the sign bit appears in another position, the value before the sign bit is retained 
parseFloat("0xa"); // 0 [note] it will not be parsed as hexadecimal.
parseFloat("010"); // 10;  [note] it will not be parsed as octal, and the result is 10
parseFloat(""); // NaN; The empty string is converted to Nan
parseFloat("1+2.3"); // 1; If the first value is a numerical value, analyze backward in turn to find continuous values until the first non numerical value is encountered, convert the previously obtained value into number and return parsefloat ("123.3ac")// 123.3;

+

+"23"                    //23
+null                    //0
+undefined               //NaN

3. Process control statement

Process control: Branch (condition), loop

Branch statement

3.1if… Else statement


Conditional statements are used to perform different actions based on different conditions.


Conditional statement

Usually when writing code, you always need to perform different actions for different decisions. You can use conditional statements in your code to accomplish this task.

In JavaScript, we can use the following conditional statements:

  • If statement-Use this statement to execute code only when the specified condition is true
  • If… Else statement-Execute code when the condition is true and other code when the condition is false
  • If… Else if…. else statement-Use this statement to select one of multiple code blocks to execute
  • Switch statement-Use this statement to select one of multiple code blocks to execute

If statement

The statement executes code only when the specified condition is true.

if (condition)
{
    Code executed when the condition is true
}

Condition represents any expression. The evaluation result of the expression is not necessarily Boolean. If it is not Boolean, ECMAScript will call the boolean() conversion function to convert the expression result to a boolean type. When the value is true, execute the content in the if code block.

If… Else statement

Use the if…. else statement to execute code when the condition is true and other code when the condition is false.

if (condition)
{
    Code executed when the condition is true
}
else
{
    Code executed when the condition is not true
}

When the condition is true, execute the contents in the if code block; otherwise, execute the contents in the else code block. Generally, if there is only one line of code in the code block, you can omit the braces.

If… Else if… Else statement

Use the if… Else if… Else statement to select one of multiple code blocks for execution.

if (condition1)
{
        statement1
    Code executed when condition 1 is true
}
else if (condition2)
{
        statement2
    Code executed when condition 2 is true
}
else
{
        statement3
      Code executed when neither condition 1 nor condition 2 is true
}

For multi condition branches, when condition1 is true, execute statement1; otherwise, when condition2 is true, execute statement2; and when condition1 and condition2 are false, execute statement3.

Comprehensive case list:
function exchange(num) {
  if (num && typeof num == 'number') {
    //typeof num=='number' && 0<num and num<=10
    if (num > 0 && num <= 10) {
      if (num == 1) {
        Result = "one";
      } else if (num == 2) {
        Result = "two";
      } else if (num == 3) {
        Result = "three";
      } else if (num == 4) {
        Result = "four";
      } else if (num == 5) {
        Result = "Five";
      } else if (num == 6) {
        Result = "land";
      } else if (num == 7) {
        Result = "seven";
      } else if (num == 8) {
        Result = "eight";
      } else if (num == 9) {
        Result = "Nine";
      } else {
        Result = "ten";
      }
    } else if(num > 10) {
      Result = "please enter a number no greater than 10";
    } else{
      Result = "please enter a number not less than 0";
    }
  } else if (num == 0) {
    Result = "zero";
  } else {
    Result = "please enter a number";
  }
  console.log(result);
}
exchange(0);
exchange(-120);
exchange(100);
exchange('as');
exchange();

3.2. Switch statement


Switch statements are used to perform different actions based on different conditions.


Use the switch statement to select one of multiple code blocks to execute.

switch(n)
{
    case 1:
        Execute code block 1
        break;
    case 2:
        Execute code block 2
        break;
    default:
        Code not executed at the same time as case 1 and case 2
}

How it works: set the expression firstn(usually a variable). The value of the expression is then compared with the value of each case in the structure. If there is a match, the code block associated with the case is executed. Please usebreakTo prevent the code from automatically running to the next case.

Case:
var d=new Date().getDay(); 
switch (d) 
{ 
  case 0:
    Console.log ('sunday ');
  break; 
  case 1:
    Console.log ('monday ');
  break; 
  case 2:
    Console.log ('tuesday '); 
  break; 
  case 3:
    Console.log ('wednesday '); 
  break; 
  case 4:
    Console.log ('thursday '); 
  break; 
  case 5:
    Console.log ('friday ');
  break; 
  case 6:
    Console.log ('saturday '); 
  break; 
}

Default keyword

Use the default keyword to specify what to do when a match does not exist:

var d = new Date().getDay();
switch (d) {
  case 4:
    Console.log ('thursday ');
    break;
  case 5:
    Console.log ('friday ');
    break;
  default:
    Console.log ('Looking forward to the weekend ');
}

be careful:

one   Break in case code block cannot be omitted

two   Default can be placed anywhere in the code, break cannot be omitted, and break can be omitted in the last position;

three   “Variable vs. constant”===“

Recommendations:

Switch is recommended for branch control for equivalence comparison, and if is recommended for non equivalence judgment

Circular statement


A loop can execute a block of code a specified number of times.


If you want to run the same code over and over again with different values each time, it’s convenient to use loops.

We can output the value of the array as follows:

var arr = [1,2,3,4,5]
for (var i=0;i<arr.length;i++)
{ 
    console.log(i)
}

Different types of loops

JavaScript supports different types of loops:

  • for-Loop the code block a certain number of times
  • for/in-Loop through the properties of the object
  • while-Loop the specified code block when the specified condition is true
  • do/while-Similarly, when the specified condition is true, loop the specified code block

3.3. For cycle

The for loop is a tool you often use when you want to create a loop.

The following is the syntax of the for loop:

For (* statement 1 *; * statement 2 *; * statement 3 *)
{
  *Executed code block*
}
for (var i=0; i<5; i++)
{
    console.log(i);
}

From the above example, you can see:

Statement 1 sets the variable (VaR I = 0) before the start of the loop.

Statement 2 defines the condition for loop operation (I must be less than 5).

Statement 3 adds a value (I + +) each time the code block has been executed.

Statement 1(code block) execute before starting

Usually, we use statement 1 to initialize the variables used in the loop (VaR I = 0).

Statement 1 is optional, that is, it is OK not to use statement 1.

You can initialize any (or more) values in statement 1.

Statement 2Define the conditions for running a loop (code block)

Generally, statement 2 is used to evaluate the condition of the initial variable.

Statement 2 is also optional.

If statement 2 returns true, the loop starts again, and if false, the loop ends.

Statement 3Execute after the loop (code block) has been executed

Typically, statement 3 increases the value of the initial variable.

Statement 3 is also optional.

Statement 3 has several uses. The increment can be negative (I –) or greater (I = I + 15).

Statement 3 can also be omitted (for example, when there is corresponding code inside the loop).

//1-100 even sum
var result = 0;
for(var i=0;i<=100;i++){
  if(i%2==0){
      result += i;
  }
} 
console.log(result);
//Bubble sorting
//1. Compare two adjacent elements. If the former is larger than the latter, exchange the position.
//2. After the first round of comparison, the last element is the largest element.
//3. At this time, the last element is the largest, so the last element does not need to participate in the size comparison.
function bubbleSort(arr) {
  var len = arr.length;
  //How many times is the outer control cycle
  for (var i = 0; i < len-1; i++) {
    //The inner layer controls the number of cycles per trip
    for (var j = 0; j < len - 1 - i; j++) {
         //Adjacent elements are compared in pairs, elements are exchanged, and large elements are exchanged to the back
        if (arr[j] > arr[j + 1]) {
            var temp = arr[j];
            arr[j] = arr[j+1];
            arr[j+1] = temp;
        }
    }
  }
  return arr;
}
//Take an array
var arr = [20,18,27,19,35];
//Use function
bubbleSort(arr)
Keyword break

If you want to exit before all iterations, you can use break. When the break is executed, it will immediately jump out of the loop body.

The difference between the keyword continue and break is that continue does not jump out of the loop. Instead, immediately end the current cycle and enter the next cycle.

for(var i=0;;i++){
  console.log(i);
  if(i==5){
    break;
  }
}

Enhanced for loop

For.. in is used to traverse the properties of an array or object

For (custom variable name in array / object){

Execute code

}

“Custom variable name” is used to specify the element index of the array or the attribute of the object

//Circular array
var arr=[10,'aa',20,30,40];
for(var i=0;i<arr.length;i++){
  console.log(i+"--"+arr[i]);
}
for(var key in arr){
  console.log(key+"--"+arr[key]);
}
//Loop object properties:
var obj = {
  name:"briup",
  age:12,
  salary:10000
};
/*
There are two ways to access properties:
objectName.propertyName
perhaps
objectName["propertyName"]
*/
console.log(obj.name);
console.log(obj["age"]);
console.log(obj.salary);
for(var key in obj){
  console.log(key+"--"+obj[key]);
}

3.4. While loop


As long as the specified condition is true, the loop can always execute the code block.


The while loop executes the code block when the specified condition is true.

grammar

While (* condition *)
{
  *Code to execute*
}
while (i<5)
{
    console.log(i);
    i++;
}
//Find the sum of 1-100
var result = 0;
var i = 1;
while(i<=100){
    result += i;
    i++;
}
console.log(result);

3.5.do/while loop

The do / while loop is a variant of the while loop. The loop executes the code block once before checking whether the condition is true, and then repeats the loop if the condition is true.

do
{
    Code to execute
}
While (condition);

The following example uses a do / while loop. The loop will execute at least once, even if the condition is false, because the code block will execute before the condition is tested:

do
{
    console.log(i);
    i++;
}
while (i<5);
//Find the sum of 1-100
var result = 0;
var i = 1;
do{
    result += i;
    i++;
} while(i<=100);
console.log(result);

3.6. Recursion

A process or function has a method to call itself directly or indirectly in its definition or description. It usually transforms a large and complex problem layer by layer into a smaller problem similar to the original problem. The recursive strategy can describe the multiple repeated calculations required in the problem-solving process with only a small number of programs, which greatly reduces the amount of code of the program.

Factorization using recursion
//Recursive popular understanding
//The function can't stop by itself
//A jump out condition is required
/*
    Factorization of n using recursion
    Suppose you have written a function factorial
    1 => 1
    2 => 1*2 ->factorial(1)*2
    3 => 1*2*3 ->factorial(2)*3
    4 => 1*2*3*4 ->factorial(3)*4
    ...
    n => 1*2*3...*n ->factorial(n-1)*n
*/
function factorial(n) {
  //Jump out condition
  if (n == 1) {
    return 1;
  }
  return factorial(n - 1) * n;
}
var result = factorial(4);
console.log(result);