Front end development foundation (JavaScript foundation I)

1, Introduction method:

1. Inline:

<input type="button" value="Let me try" onclick="alert('Hello World')" />
  • You can write a single line or a small amount of JS code in the event attribute of the HTML tag (the attribute starting with on), such as onclick
  • Note the use of single and double quotation marks: we recommend using double quotation marks in HTML and single quotation marks in JS
  • Poor readability, inconvenient to read when writing a large amount of JS code in html;
  • Quotation marks are easy to make mistakes. When quotation marks are nested and matched in multiple layers, they are very easy to be confused;
  • Use under special circumstances

2. Built in:

<script>
    alert('Hello  World~!');
</script>

3. External file type:

<script src="my.js"></script>
  • It is conducive to the structure of HTML page code, and a large section of JS code is independent of HTML page, which is not only beautiful, but also convenient for file level reuse
  • No code can be written in the middle of the script tag that references the external JS file
  • It is suitable for a large amount of JS code

2, JavaScript output statement:

method                     	explain                      	ascription
alert(msg)	           Browser pop-up alert box	               browser
console.log(msg)	Browser console printout information	           browser
prompt(info)	  The browser pops up an input box, which can be entered by the user	       browser

3, Variable:

1. Variable declaration:

//  Declare variable  
var age; //  Declare a variable named age  
  • var is a JS keyword used to declare variables (the meaning of variable variable). After using this keyword to declare a variable, the computer will automatically allocate memory space for the variable, which does not need to be managed by the programmer
  • age is the variable name defined by the programmer. We need to access the allocated space in memory through the variable name

2. Variable assignment:

age = 10; // Assign a value of 10 to this variable
  • =It is used to assign the value on the right to the variable space on the left, which means assignment
  • The variable value is the value that the programmer saves in the variable space

3. Variable initialization:

var age  = 18;  // The declared variable is also assigned a value of 18
// Declaring and assigning a variable is called variable initialization.

4. Variable extension

  • Update variable
    After a variable is re assigned, its original value will be overwritten, and the variable value will be subject to the last assigned value.
var age = 18;
age = 81;   // The end result is 81 because 18 is covered  
  • Declare multiple variables at the same time
    When declaring multiple variables at the same time, you only need to write a var, and the names of multiple variables are separated by English commas.
var age = 10,  name = 'zs', sex = 2;
  • Declare variable special cases
situation											explain								result
var age ;console.log (age);				Declare only without assignment						undefined
console.log(age)					No declaration, no assignment, direct use					report errors
age = 10; console.log (age);			No declaration, only assignment						10

5. Variable naming conventions:

  • Consists of letters (A-Za-z), numbers (0-9), underscores () Dollar sign ($), such as usrage, num01_ name
  • Strictly case sensitive. var App; And var App; Are two variables
  • Cannot start with a number. 18age is wrong
  • Cannot be keyword or reserved word. For example: var, for, while
  • Variable names must be meaningful. MMD BBD nl → age
  • Follow the hump nomenclature. The first letter is lowercase, and the first letter of the following word needs to be capitalized. myFirstName

4, Data type:

1. Digital range

  • Maximum value: number MAX_ Value: 1.7976931348623157e+308
  • Minimum value: number MIN_ Value: 5e-32

2. The digital type has three special values:

  • Infinity, representing infinity, greater than any value
  • Infinity, representing infinitesimal, less than any value
  • NaN, Not a number, represents a non numeric value

3,isNaN:

  • It is used to judge whether a variable is of non numeric type and returns true or false

    4. Undefined and Null:
  • A variable that has not been assigned a value after declaration will have a default value of undefined (pay attention to the result when connecting or adding)
var variable;
console.log(variable);           // undefined
console.log('Hello' + variable);  // Hello, undefined
console.log(11 + variable);     // NaN
console.log(true + variable);   //  NaN
  • A declared variable is given a null value, and the value stored in it is null (when learning objects, we continue to study null)
var vari = null;
console.log('Hello' + vari);  // Hello, null
console.log(11 + vari);     // 11
console.log(true + vari);   //  1

5. Get the data type of the variable:

typeof can be used to get the data type of the detection variable

var num = 18;
console.log(typeof num) // Result number


6. Data type conversion:

The data obtained by using the form and prompt is of string type by default. At this time, you can't simply add directly, but you need to convert the data type of the variable

(1) Convert to string:

  • toString() and String() are used differently.
  • There are three conversion methods, and the third plus sign splicing string conversion method is also called implicit conversion.

(2) Convert to digital:

  • Pay attention to the case of parseInt and parseFloat words, which are the key points
  • Implicit conversion is that JS automatically converts data types when we perform arithmetic operations

(3) Convert to Boolean:

  • Values representing null and negative will be converted to false, such as' ', 0, NaN, null and undefined
  • The remaining values are converted to true
console.log(Boolean('')); // false
console.log(Boolean(0)); // false
console.log(Boolean(NaN)); // false
console.log(Boolean(null)); // false
console.log(Boolean(undefined)); // false
console.log(Boolean('Xiaobai')); // true
console.log(Boolean(12)); // true

5, Keywords and reserved words

1. Identifier:

identification(zhi)Character: refers to the name given by the developer for variables, attributes, functions and parameters.
Identifiers cannot be keywords or reserved words.

2. Keywords:

Keyword: refers to JS Words that have been used by themselves can no longer be used as variable names and method names.
include: break,case,catch,continue,default,delete,do,else,finally,for,function,if,in,instanceof,new,return,switch,this,throw,try,typeof,var,void,while,with Wait.

3. Reserved words:

Reserved words: actually, they are reserved "Keywords", which means that although they are not keywords now, they may become keywords in the future. Similarly, they cannot be used as variable names or method names.
include: boolean,byte,char,class,const,debugger,double,enum,export,extends,fimal,float,goto,implements,import,int,interface,long,mative,package,private,protected,public,short,static,super,synchronized,throws,transient,volatile Wait.
Note: if a reserved word is used as a variable name or function name, it is likely that no error message will be received unless the reserved word is implemented in a future browser. When the browser implements it, the word will be regarded as a keyword, so a keyword error will appear.

5, Operator (operator)

1. Arithmetic operator

Concept: the symbol used in arithmetic operation, which is used to perform the arithmetic operation of two variables or values

  • Floating point precision problem
    The highest precision of floating-point values is 17 decimal places, but it is far less accurate than integers in arithmetic calculations.
var result = 0.1 + 0.2;    // The result is not 0.3, but 0.300000000000000 4
console.log(0.07 * 100);   // The result is not 7, but 7.000000000000001
 So: do not directly judge whether two floating-point numbers are equal !

2. Increment and decrement operators

If you need to add or subtract 1 from a numeric variable repeatedly, you can use increment(++)And decreasing( -- )Operator.
stay JavaScript Medium, increasing(++)And decreasing( -- )It can be placed either before or after the variable. When placed in front of a variable, we can call it a pre increment (decrement) operator, and when placed behind a variable, we can call it a post increment (decrement) operator.
Note: increment and decrement operators must be used with variables. 

(1) Increment operator

  • Pre increment operator
    ++Increment before num is self adding 1, which is similar to num = num + 1, but + + num is easier to write.
    Use the formula: add first and then return the value
var  num = 10;
alert(++num + 10);   // 21
  • Post increment operator
    Num + + Post increment is self adding 1, which is similar to num = num + 1, but num + + is easier to write.
    Use the formula: first return the original value, and then add it by yourself
var  num = 10;
alert(10 + num++);  // 20

3. Comparison operator

Concept: comparison operator (relational operator) is the operator used when comparing two data. After the comparison operation, a Boolean value (true / false) will be returned as the result of the comparison operation.


4. Logical operator

Concept: a logical operator is an operator used for Boolean operations, and its return value is also a Boolean value. In the later development, it is often used to judge multiple conditions

  • Logic and&&
    True is returned only when both sides are true, otherwise false is returned

  • Logical or||
    True is returned only when both sides are true, otherwise false is returned

  • Logical non!
    Logical non (!) Also called negation, it is used to take a value opposite to a Boolean value. For example, the opposite value of true is false

var isOk = !true;
console.log(isOk);  // false

(1) Short circuit operation (logic interrupt)

  • Logic and
    Syntax: expression 1 & & expression 2
If the value of the first expression is true, expression 2 is returned
 If the value of the first expression is false, the expression 1 is returned
console.log( 123 && 456 );        // 456
console.log( 0 && 456 );          // 0
console.log( 123 && 456&& 789 );  // 789
  • Logical or
    Syntax: expression 1 | expression 2
- If the value of the first expression is true, the expression 1 is returned
- If the value of the first expression is false, expression 2 is returned
console.log( 123 || 456 );         //  123
console.log( 0 ||  456 );          //  456
console.log( 123 || 456 || 789 );  //  123

5. Assignment operator

var age = 10;
age += 5;  // Equivalent to age = age + 5;
age -= 5;  // Equivalent to age = age - 5;
age *= 10; // Equivalent to age = age * 10;

6. Operator priority

  • The logical non priority in unary operators is very high
  • Logical and have higher priority than logical or

6, Process control

Simple understanding: process control is to control the execution of code according to a certain structural order
There are three main structures of process control, namely sequence structure, branch structure and loop structure, which represent the execution order of the three codes

1. Branch process control:

In the process of executing code from top to bottom, different path codes are executed according to different conditions (the process of executing one or more codes), so as to get different results
JS language provides two branch structure statements: if statement and switch statement

  • if statement
// If the condition is true, execute the code, otherwise do nothing
if (Conditional expression) {
    // Code statement executed when the condition is satisfied
}

  • if else statement
// If the condition is true, execute the code in if, otherwise execute the code in else
if (Conditional expression) {
    // [if] the condition is true, the code to be executed
} else {
    // [otherwise] executed code
}
  • if else if statement (multi branch statement)
// Suitable for checking multiple conditions.
if (Conditional expression 1) {
    Statement 1;
} else if (Conditional expression 2)  {
    Statement 2;
} else if (Conditional expression 3)  {
   Statement 3;
 ....
} else {
    // None of the above conditions holds. Execute the code here
}

2. Ternary expression:

Expression 1 ? Expression 2 : Expression 3;
  • If expression 1 is true, the value of expression 2 is returned; if expression 1 is false, the value of expression 3 is returned
  • Simple understanding: it is similar to the abbreviation of if else

3. switch branch process control

switch Statement is also a multi branch statement, which is used to execute different code based on different conditions. When you want to set a series of options for a specific value for a variable, you can use switch. 
switch( expression ){ 
    case value1:
        // Code to execute when expression equals value1
        break;
    case value2:
        // Code to execute when expression equals value2
        break;
    default:
        // Code to execute when the expression is not equal to any value
}
  • Switch: switch conversion, case: small example option
  • The keyword switch can be followed by an expression or value in parentheses, usually a variable
  • Keyword case, followed by an expression or value of an option, followed by a colon
  • The value of the switch expression is compared with the value of the case in the structure
  • If there is matching congruence (= = =), the code block associated with the case will be executed and stopped when a break is encountered, and the code execution of the whole switch statement will end
  • If the values of all case s do not match the values of the expression, execute the code in default
  • Note: when executing the statement in the case, if there is no break, continue to execute the statement in the next case

(1) Differences between switch statement and if else statement:

  • In general, their two statements can be replaced with each other
  • The switch... Case statement usually handles the case where the value is determined by comparison, while the if... else... Statement is more flexible and is often used to judge the range (greater than or equal to a certain range)
  • The switch statement directly executes the conditional statement of the program after conditional judgment, which is more efficient. if... else statements have several conditions, you have to judge how many times.
  • When there are few branches, the execution efficiency of if... else statement is higher than that of switch statement.
  • When there are many branches, the execution efficiency of switch statement is higher and the structure is clearer.

Non original, knowledge porter on the network.

Keywords: Javascript Front-end

Added by justinchrono on Wed, 19 Jan 2022 08:23:47 +0200