The operator

Operator classification

  • The Arithmetic operator

  • The Comparison operator

  • The Logical operator

  • Assignment operator Assognment operator

  • Bitwise operator

  • The conditional (ternary) operator Condition operator

1. Mathematical operators

1.1 Mathematical operators

Operators: +, -, *, /, %, ++, –, (),

Operation order: multiply and divide mod, then add and subtract, priority parentheses

Range of remainder: [0, divisor -1]

  1. A purely numeric string is implicitly converted to a numeric type when it is operated on (except for addition)

    console.log("12" - 2)	/ / 10
    console.log("12" * 2)	/ / 24
    Copy the code
  2. Special strings and booleans are also implicitly converted when operating on numbers

    true ==> 1

    fasle ==> 0

    null ==> 0

    console.log(5 * true)	/ / 5
    console.log(5 * false)	/ / 0
    console.log(5 * null)	/ / 0
    console.log(5 + true)	/ / 6
    Copy the code
  3. Undefined and other strings and numbers, resulting in NaN (except concatenation)

    console.log(5 * undefined)	// NaN
    console.log(5 * 'hello')	// NaN
    console.log(5 * NaN)	// NaN
    Copy the code
  4. Infinity

    console.log(5 + Infinity)	// Infinity
    console.log(5 - Infinity)	// -Infinity
    console.log(5 * Infinity)	// Infinity
    console.log(5 / Infinity)	/ / 0
    console.log(5 % Infinity)	/ / 5
    Copy the code

1.2 Mathobject

Powerful math objects built into JavaScript, including all properties and methods in math

Math.random()

Random number, which randomly generates a number greater than or equal to zero and less than one [0, 1]

Math.pow(num, power)

Calculation of powers, num: base, power: power

Math.sqrt(num)

Square calculation, num: square number

Math.PI

The value of PI.

console.log(Math.random())		/ / random number
console.log(Math.pow(2.3))		/ / 8
console.log(Math..sqrt(81))		/ / 9
console.log(Math.PI)		/ / 3.141592653589793
Copy the code

2. Compare operators

Operators: >, <, ==, ===, >=, <=,! =,! = =,

Comparison operators participate in operations that result in booleans (true/false)

  1. A purely numeric string is compared to a number for implicit conversion

  2. True, false, null, and implicit conversions are also performed for comparisons

    true==>1 false==>0 null==>0

    However, null does not equal 0 when performing the operations == and ===

    console.log(null= =0)		//false 
    console.log(null= = =0)		//false 
    console.log(null> =0)		// true
    console.log(null< =0)		// true
    Copy the code

    ==: Only judge the value; ===: Determine both the value and the type

  3. ! = contrary to = contrary to; ! == is the opposite of ===

    I’m just going to check == and === and then I’m going to invert it

  4. NaN performs comparison operations

    console.log(NaN= =NaN)		// false
    Copy the code
  5. Infinity for comparison

    console.log(Infinity= =Infinity)		// true
    console.log(Infinity= = =Infinity)		// true
    Copy the code
  6. The comparison operation of impure numeric strings does not compare the length of strings, but the Unicode encoding of characters. The first character is less than the last. If the first character is equal, the first character is compared backwards.

    Number (0-9) < Uppercase (A-Z) < Lowercase (A-z)

    console.log('12' < '2')		// true
    console.log('banana' < 'back')		// true
    Copy the code

3. Logical operators

Operator:

Logic and operations: &&

Logical or operation: | |

Logical non-operation:!

Boolean operations usually involve Boolean operations, and the result is Boolean (true/false)

  • Logic and

    True is true and false is false

  • Logic or

    A true true, with false only false

  • Logic is not

    Take antitruth -> false false -> true

  1. Strings or numbers or special fields that participate in a logical operation are automatically converted to Boolean values that participate in the operation

    NaN, 0, “(empty string), null, undefined ===> fasle

    Non-zero number, non-empty string, Infinity ===> true

  2. Short grammar

    • Logic && : ===> series circuit:

      If A is true, the current can flow to B, which is b

      If A is false, the current cannot flow to B, and the result is A

    • Logic or | | : = = = > parallel circuit:

      If A is true, the current can complete the cycle from A, and the result is A

      If A is false, the current flows to B to complete the cycle and the result is B

      console.log('123' && true)		// true
      console.log('123' || true)		/ / '123'
      console.log(' ' && true)			/ /"
      console.log(' ' || true)			// true
      console.log(NaN && false)		// NaN
      console.log(NaN || false)		// false
      console.log(NaN && true)		// true
      console.log(NaN || true)		// true
      console.log(0 && '1')			/ / 0
      console.log(0 || '1')			/ / '1'
      console.log(undefined && 'hello') // undefined
      console.log(undefined || 'hello') // 'Hello'
      console.log(null && 'hello') // null
      console.log(null || 'hello') // 'Hello'
      console.log(Infinity && 'hello') // 'Hello'
      console.log(Infinity || 'hello') // Infinity
      Copy the code

      conclusion

      If &&: a -> false, it is a; otherwise, it is B

      Or | | : a - > true, is a, or b

  3. The order in which logical operators operate

    Non! > and && > or | |

false || !false && false || true
/ / the first
//fasle || true && false || true
/ / in
//false || false || true
/ / the or
//false || true
// true
Copy the code
4 && 'hello' || !false || !true && null
/ / the first
//4 && 'hello' || true || false && null
/ / in
//'hello' || true || false
/ / the or
//'hello' || false
/ / "hello"
Copy the code

4. Operator synthesis operation

Order of operations

Close-fitting (! ++ --) > Math > Comparison > Logic > Assignment

var a = 4;
var sum = 1 * (2 + 3) && a++ || 5 > 6 && 7 < 8 || 9
/ / close
1 * (2 + 3) && 4 || 5 > 6 && 7 < 8 || 9
/ / math
5 && 4 || 5 > 6 && 7 < 8 || 9
/ / to compare
5 && 4 || false && true || 9
/ / logic
4 || false || 9
/ / logical or
4
Copy the code
var a = 4;
var sum = 1 + 2 && 3 * a++ % 5 || 6 < 7= =8/!false
/ / close
1 + 2 && 3 * 4 % 5 || 6 < 7= =8 / true
/ / math
3 && 2 || 6 < 7= =8
/ / to compare
3 && 2 || true= =8
3 && 2 || false
/ / logic
2 || false
/ / logical or
2
Copy the code

Flow control statement

JavaScript is usually executed from top to bottom, but you can control the order of execution using flow control statements

  • Sequential structure
  • Branching structure
    • If statement
    • Ternary expression
    • A switch statement
  • Loop structure
    • The for loop
    • Do - while statement
    • While statement

Conditional branch statement

1. If statements

1.1 Single IF statement

grammar

if(Condition) {structure// If the condition is true, execute
} else{structure// If the condition is false, execute
}
Copy the code

Note: When the structure has only one JavaScript statement, the braces can be omitted

If executor else executor

var a= parseInt(prompt("Please enter your score"));
if (a >= 60) {
  alert("Pass the exam");
} else {
  alert("Fail");
}
The parseInt() function parses a string and returns an integer.
//prompt() is used to prompt the user for the input dialog box.
Copy the code
1.2 Multi-branch IF Statement (Jumping phenomenon)

grammar

if(conditions1) {structure// If condition 1 is true, execute
} else if(conditions2) {structure// Execute if condition 1 is false and condition 2 is true
} else{structure// Execute when conditions 1 and 2 are false
}
Copy the code

Jumping phenomenon

A multi-branch if statement that jumps off a building will execute only one of its constructs.

var a= parseInt(prompt("Please enter your score"));
if (a >= 90) {
  alert("Good");
} else if (a >= 80) {
  alert("Good");
} else if (a >= 60) {
  alert("Pass");
} else {
  alert("Fail");
}
// Only one structure can be executed
Copy the code
var a= parseInt(prompt("Please enter an integer within 10."));
if (a <= 3) {
  alert(a += 2);    // A
} else if (a <= 5) {
  alert(a += 2);    // B
} else if (a <= 8) {
  alert(a += 3);    // C
} else {
  alert(a ++);    // D
}
// when a=8, execute structure C, result = 11
// execute structure B when a=5, result = 7
// execute structure A when a=2, result = 4
// A can execute only one structure in ABCD
Copy the code
1.3 Nesting of if statements

An if statement can be nested within the structure of an if statement

var sex = prompt("Input gender");
var age = parseInt(prompt("Input age"));

if (sex === "Male") {
  if (age >= 22) {
      alert("Marriageable");
  }else {
      alert("No marriage."); }}else if (sex == "Female") {
  if (age >= 20) {
      alert("Marriageable");
  }else {
      alert("No marriage."); }}Copy the code

2. Ternary expressions (operators)

Syntax: Conditional expressions? Value 1: Value 2

When the conditional expression JIS is true, the value is 1; When the conditional expression is false, the value is 2;

Eg1: Calculate the maximum value of a, B and C

var a, b, c;
function max(a, b, c) {
  return a > c ? (a > b ? a : b): (b > c ? b : c);
}
console.log(max(2.3.5));
/ / 5
Copy the code

Conclusion: Ternary representations are also conditional branching statements. This is often used when there are two possible ways to assign a value to a variable

Eg2: Calculate year-end bonus

If the working years are less than one year and the salary is less than 8K, the year-end bonus is one time of the salary; otherwise, it is 1.2 times

When the working years are less than two years and the salary is less than 10K, the year-end bonus is 1.5 times of the salary, otherwise it is 1.7 times

When the working years are less than three years and the salary is less than 13K, the year-end bonus is 2.3 times of the salary, otherwise it is 3 times

var salary = parseInt(prompt("Please enter your salary"));
var year = parseInt(prompt("Please enter your years of service"));
var beishu ;
if (year === 0) {
  beishu = salary < 8000 ? 1 : 1.2;
} else if (year === 1) {
  beishu = salary < 10000 ? 1.5 : 1.7;
} else {
  beishu = salary < 13000 ? 2.3 : 3;
}
console.log("What is your annual bonus?" + salary*beishu);
Copy the code

3. The switch statement

The switch statement is also a conditional branching statement that allows a program to evaluate an expression and match the value to a case option. If the match is successful, the structure in that case is executed directly

grammar

switch (expression) {
  case label1:
    // To match label1, execute statements1
    statements1;
    break;
  case label2:
    // Execute statements2 to match label2
    statements2;
    break;
  default:
    break;
}
Copy the code

Break: indicates that the switch statement is forced to break. If it is not written, the structure will be executed even if the following case is not met.

Eg1: Output the number of days per month using break

var month = parseInt(prompt("Please enter a month"));
switch (month) {
  case 1:
  case 3:
  case 5:
  case 7:
  case 8:
  case 10:
  case 12:
    alert("The month has 31 days.");
    break;
  case 2:
    alert("The month has 28 days.");
    break;
  default:
    alert("The month has 30 days.");
    break;
}
// When a case is followed by an expression, the program evaluates the expression first
Var a =5, b = 3; case a + b ==> case 8
Copy the code

Summary: If ternary expression switch statement usage

If statement: most commonly used and versatile

Ternary expression: suitable for variable assignment of two options

Switch statement: This is used when a value matches multiple cases

Looping statements

1. The for loop

The for loop is a prejudgment, which evaluates the conditional expression first

grammar

For (initializes the expression; Boolean expression; Update expression) {

Looping statements

}

for (let i = 0; i < 100; i++) {
  console.log("This is number one." + i + "Secondary output");
}
console.log("Output end");
// let I = 0
/ / (2) I < 100
// ③console.log(" this is the "+ I +" output ");
/ / (4) i++
// ⑤console.log(" output ended ");
Copy the code

The for loop is executed first (①) and only once, and then (②). If the result is false, jump out of the for loop and execute ⑤. If it is true, execute (③ -> ④ -> ②). If ② is false, execute ⑤ as above.

var i = 3
for (console.log(i++); i < 13; i += 5) {
  console.log(i);
}
/ / 3, 4, 9
/ / (1) the console. The log (i++)
/ / (2) I < 13
/ / (3) the console. The log (I);
/ / (4) the I + = 5
Copy the code

First execute ①, output 3, then execute ②, judge true, then execute ③, output 4, then execute ④, I becomes 9, execute ② again, judge true, then execute ③, output 9, then execute ④, I becomes 14, then execute ② again, judge false, and jump out of the loop

For loops can nest for loops (I, j, k)

Multiplication table/addition table

For loops can nest if loops (I, j, k)

for (let i = 4; i < 20; i+=5) {
  if (i % 2) {
    console.log(i); }}/ / September 19
Copy the code
// The number of daffodils with three digits.
for (let i = 100; i <= 999; i++) {
  let ge = i % 10;
  let shi = parseInt(i / 10) % 10;
  let bai =parseInt(i/ 100);
  let sum = Math.pow(ge, 3) + Math.pow(shi, 3) + Math.pow(bai, 3)
  if (i === sum) {
    console.log(i); }}// 153 370 371 407
Copy the code
/ / accumulation
// var num = parseInt(prompt(" please enter a positive integer "));
var num = 9;
var sum = 0;
for (let i = 0; i < num; i++) {
  if (num % i === 0) {
    sum ++;
    console.log(i); }}console.log(num + "When the total divisor of" + sum);
/ / 1
/ / 3
// The total divisor of 9 is 2
Copy the code
/ / multiplicative
// var num = parseInt(prompt(" please enter a positive integer "));
var num = 5;
var cheng = 1;
for (let i = 1; i <= num; i++) {
  cheng *= i
}
console.log(cheng);
/ / 120
Copy the code

2. Do while loop statements

Do while loop statement is a post-test loop statement, first execute the structure, then judge the expression, meet the condition to continue to execute, do not meet directly jump out.

grammar

do {

The structure of the body

} while (expression);

var i = 3; // Loop variables must be written outside the loop statement
do {
  i += 4;
  console.log(i);
} while (i<25);
// 7 11 15 19 23 27
Copy the code

Note: The structure in the do while loop is executed unconditionally once

var i = 3;
do {
  console.log(i);
} while (i<3);
/ / 3
Copy the code

3. While loop statement

The do while loop is a pre-test loop and is not recommended. Use the for loop instead. Loop through a piece of code until a false condition is encountered, terminating the statement

grammar

While (expression) {

The structure of the body

}

// Output first, increment later
var i = 3;
while (i<25) {
  console.log(i);
  i+=4;
}
// 3 7 11 15 19 23

// First increment, then output
var i = 3;
while (i<25) {
  i+=4;
  console.log(i);
}
// 7 11 15 19 23 27
Copy the code

Note: The order in which loop statements are added affects their output

break & continue

break

  1. When the break keyword is encountered, the current statement (for do-while while switch) is terminated, giving control of the statement to the statement following the loop

    for (let i = 1; i < 100; i+=2) {
      if (i % 3= = =0) {
        console.log(i);
        break; }}/ / 3
    Copy the code
  2. In a nested for loop, a break can only control the inner for loop and cannot terminate the outer loop

    for (let i = 1; i < 5; i++) {
      for (let j = 1; j < 5; j++) {
        if (j == 2) {
          break;
          // This break can only manage j, not I
        }
        console.log(i, j); }}/ / 1 1
    1 / / 2
    / 1/3
    / 1/4
    Copy the code

continue

  1. When conditions are met, a continue only terminates the current statement, not the loop

    for (let i = 1; i < 5; i++) {
      for (let j = 1; j < 5; j++) {
        if (j === 2 || i === 4) {
          continue;
          // Manage only the inner for loop
        }
        console.log(i, j); }}/ / 1 1
    / / 1 3
    / / 1 4
    1 / / 2
    / / 2, 3
    / / 2, 4
    / 1/3
    / / 3. 3
    / / 3 4
    Copy the code
  2. When you want to control the outer loop, you need the tag to control it

Note: Break and continue can be used for JHF computer execution

Principle: when a number is a sum number, the number and performance development of the number I, in less than or equal to I must be a factor of the number

// var num = parseInt(prompt(" please enter a positive integer "));
var num = 17
// See if there are any divisor other than 1 before taking the square root of the number
for (let i = 2; i < Math.sqrt(num); i++) {
  if (num % i === 0) {
    // As long as a divisor is found, the Buddha ru loop is ended
    break;
  }
  console.log(num + "Is prime.");
}
Copy the code
// Prints primes between 1 and 10(1000)
out:for (let i = 2; i <= 10; i++) {
  for (let j = 2; j < Math.sqrt(i); j++) {
    if (i % j === 0) {
      continueout; }}console.log(i + "Is prime.");
}
// 2 is prime
// 3 is prime
// 4 is prime
// 5 is prime
// 7 is prime
// 9 is prime
Copy the code