Basic JavaScript syntax (I)
1, Basic concepts
1. Programming
Programming: the process of making a computer write program code in a programming language to solve a problem and get the results
Computer program: it is a set of instructions for a series of problems executed by the computer, and all the programs are written in the language we master. Therefore, if people want to control the computer, they must send commands to the computer through the computer language
2. Computer language
Computer language refers to the language used for communication between people and computers. It is the medium of transmitting information between people and computers. There are many kinds of computer languages. Generally speaking, the course can be divided into three categories: machine language, assembly language and high-level language
3. Programming language
We can control the machine through a "language" similar to human language and let the computer do things for us. Such a language is called computer language
Programming language is a series of instructions used to control the computer. It has inherent format and vocabulary (the format and vocabulary of different programming languages are different), which must be observed
Nowadays, there are two common programming languages: assembly language and high-level language
- Assembly language and machine language are essentially the same. They operate directly on hardware, but the instructions use English abbreviation identifiers, which are easy to identify and remember
- High level language is mainly relative to low-level language. It does not refer to a specific language, but includes many programming languages
4. The difference between programming language and markup language
Programming language: strong logic and behavior ability. In the programming language, there are many instructions with logic and behavior ability, which is vivid
Markup Language: different from issuing instructions to the computer, it is often used for formatting and linking. Markup language exists to be read. This is passive
5. Summary
- Computers can help humans solve some problems
- Programmers use programming language to write programs and send instructions to control the computer to realize these tasks
- Programming languages include machine language, assembly language and high-level language
- A high-level language requires a compiler to convert it into a machine language recognized by the computer
6. Fundamentals of computer
Computer composition
Hardware
-
input device
-
output device
-
CPU
- Responsible for data processing and operation
-
Hard disk
-
Memory
- Both hard disk and memory are responsible for storing data. Hard disk permanently stores data and memory temporarily stores data
Software
- systems software
- Windows,Linux,macOS
- Application software
data storage
-
The computer uses binary to represent data
-
All data, including files and pictures, are finally stored in the hard disk in the form of binary data
-
All programs, including the operating system, are essentially all kinds of data, which are also stored in the hard disk in the form of binary data. What we usually call installing software is actually copying the program files to the hard disk
-
Both hard disk and memory store binary data
-
Storage unit
bit < byte < kb < MB < GB < TB
1byte = 8 bit / others are similar to 1 KB = 1024 byte
Program running
-
When opening a program, first load the program code from the hard disk into memory
-
The CPU executes code in memory
Note: the important reason for memory is that the CPU runs too fast. If you just read data from the hard disk, you will waste CPU performance. Therefore, faster access memory is used to save run-time data
2, New JavaScript
1. Introduction to JS
JavaScript is a scripting language that runs on the client side
- Scripting language: there is no need to compile. The js interpreter (js) engine interprets and executes it line by line during operation
Now it can also be based on node JS technology for server programming
Introduction to browser execution JS
- Rendering engine: used to parse HTML and CSS, commonly known as kernel
- JS engine: also known as JS interpreter. Used to read the JS code in the web page and run it after processing
- The browser itself does not execute JS code, but executes JS code through the built-in JS engine (interpreter). When the JS engine executes the code, it interprets the source code of each sentence line by line (converted into machine language) and then executed by the computer. Therefore, JS language is classified as script language and will be interpreted and executed line by line
Composition of JS
- JavaScript syntax: ECMAScript
- Page document object model: DOM
- Through the interface provided by DOM, you can operate various elements on the page (size, color, position, etc.)
- Browser object models: BOM
- Through BOM, you can operate the browser window, such as pop-up box, control browser jump, obtain resolution, etc
2. JS initial experience
JS has three writing positions: inline, inline and external
-
Inline
-
<!-- Embedded, pop-up warning box --> <input type="button" value="Tang Bohu" onclick="alert('Sister Qiu Xiang')">
- You can write a single line or a small amount of JS code in the event attribute of the HTML tag (starting with on)
- Note the use of single and double quotation marks: double quotation marks are recommended in HTML and single quotation marks are recommended in JS
- Poor readability. It is 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, it is very easy to get confused
- Use under special circumstances
-
-
embedded
-
<!-- Write in header label --> <script>alert("js")</script>
- Multiple lines of JS code can be written to the < script > tag
-
-
External type
-
alert("A warning box")
-
<!-- External import --> <script src="./homework.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 applicable to the case with a large amount of JS code
-
3. JS notes
// Single line comment Ctrl +/ /* This is the default for multiline comments: Shift + Alt + A */
4. Input and output
In order to facilitate the input and output of information, JS provides some input and output statements
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 |
<script> prompt("Please enter your age"); // This is an input box alert("Pop up warning box"); // Pop up the warning box and output the information displayed to the user console.log("I'm what programmers can see"); // Console output </script>
3, Variable
1. Main functions of variables
A variable is a container for storing data. We can get the data through the variable name, and even the data can be modified
Variable is the space that the program requests in memory to store data
2. Use of variables
Variables are used in two steps: 1 Declare variable 2 assignment
Declare variable
var age; // Declare a variable named age
- var is a JS keyword used to declare variables. After using this keyword to declare variables, the computer will automatically allocate memory space for variables, which does not need to be managed by programmers
- age is the variable name defined by the programmer. We need to access the allocated space in memory through the variable name
assignment
age = 10; // Assign a value of 10 to this variable console.log(age); // Output results
- It is used to assign the value on the right to the variable space on the left
- The variable value is the value that the programmer saves in the variable space
Variable initialization
var age = 18; // The variable is declared with a value of 18
The simultaneous assignment of declared variables is called variable initialization
Small case
var name; name = prompt("Please enter your name"); // After entering the name, it is stored in a name variable alert(name); // Output name
3. 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
Declare multiple variables
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 = 18; var name = "Li Hua"; // It's too troublesome to write like this. You can write like this var age = 18, name = "Li Hua";
exceptional case
situation | explain | result |
---|---|---|
var age; console.log(age) | Declare only variables without assignment | underfined |
console.log(age) | No declaration, no assignment, direct use | report errors |
age = 10;console.log(age) | No declaration, only assignment | 10 |
4. Naming conventions
- It consists of letters, numbers, underscores and dollar characters
- Strictly case sensitive
- Cannot start with a number, 18age is wrong
- Cannot be keyword or reserved word
- Variable names must be meaningful
- Follow the hump nomenclature. The first letter is lowercase, the first letter of the following word is uppercase, myFirstName
5. Exchange variable
var name1 = "lihua"; var name2 = "xiaoming"; // Exchange names var temp = name1; // temp stores temporary values name1 = name2; name2 = temp;
4, Data type
1. Introduction to data types
In the computer, the storage space occupied by different data is different. In order to divide the data into data with different memory sizes and make full use of the storage space, different data types are defined
2. Data type of variable
Variables are where values are stored. They have names and data types. The data type of a variable determines how bits representing these values are stored in computer memory. JS is a weakly typed or dynamic language. This means that there is no need to declare the type of variable in advance, and the type will be determined automatically during the operation of the program
var num; // Not sure what data type it is num = 10; // Number type num = "hello"; // After re assignment, it becomes a string type
When the code runs, the data type of the variable is determined by the JS engine according to the data type of the variable value on the right. After running, the variable determines the data type
js is a dynamic language, and the data types of variables can be changed
3. Simple data type
JS divides data types into two categories
- Simple data type (Number, String, Boolean, Undefined, Null)
- Complex data type (object)
data type | explain | Default value |
---|---|---|
Number | Numeric type, including integer value and floating point value | 0 |
Boolean | Boolean value | false |
String | String type | "" |
Undefined | var a; Variable declared but not assigned | undefined |
Null | var a = null; Declared that variable a is null | null |
Digital type
Digital hexadecimal
The most common base systems are binary, octal, hexadecimal and decimal
var num1 = 010; // The number preceded by a 0 represents octal console.log(num1) var num2 = 0x9; // The number preceded by 0x represents hexadecimal
Digital range
Maximum and minimum values in JS
alert(Number.MAX_VALUE); // 1.79769e + 308 alert(Number.MIN_VALUE); // 5e - 324
Special value
alert(Infinity); // Infinity, greater than any value alert(-Infinity); // Infinitesimal, less than any value alert(NaN); // Represents a non numeric value // isNaN() this method is used to judge non numbers and return a Boolean value console.log(isNaN(12)); // The return value is false
String type
String type can be any text in quotation marks, and its syntax is double quotation mark '', single quotation mark ''
- Because the attributes in HTML tags use double quotation marks, JS recommends using single quotation marks here
String quote nesting
JS can use single quotation marks to nest double quotation marks, or use double quotation marks to nest single quotation marks (outer double inner single, outer single inner double)
String escape character
Similar to the special characters in HTML, there are also special characters in the string, which we call escape characters
Escape characters start with \, which are commonly used escape characters
Escape character | interpretative statement |
---|---|
\n | Line feed |
\|Diagonal bar \ escape | |
\' | Single quotation mark |
\" | Double quotation mark |
\t | indent |
\b | Space |
String length
Detects the length of the fetch string
A string is composed of several characters. The number of these characters is the length of the characters. The length of the entire string can be obtained through the length property of the string
var str = "my name is make"; console.log(str.length); // Print the length of the string
String splicing
- Multiple strings can be spliced with + in the form of string + any type = new string after splicing
- Splicing will convert any type of string added with the string into a string, and then splice it into a new string
console.log("desert" + "camel"); // String splicing+ // As long as a string is spliced with other types, the final result is a string type console.log("1" + 18 + true); // The output is 118true
strengthen
var age = 18; console.log("i am" + age + "year"); // Variable splicing
Boolean type
Boolean types have two values: true and false
- When Boolean numbers are treated as numbers, true is 1 and false is 0
Nudefined and Null
A declared variable that is not assigned a value will have a default value of undefined
A declared variable has a null value, and the stored value is null
var vari = undefined; var flag = 10; console.log(vari + flag); // The result is NaN var space = null; console.log(space + flag); // Return 10
4. Get data type
typeof can be used to detect the data type of a variable
var num = 10, str = "lihua", flag = true, vari = undefined; console.log(typeof num); console.log(typeof str); console.log(typeof flag); console.log(typeof vari);
The value obtained by prompt is a data type of string type
Literal: the representation of a fixed value in source code
5. Conversion of data types
The data obtained by using the form and prompt is string data by default. At this time, you can't add directly and simply, but you need to convert the data type of the variable. Generally speaking, it is to convert a variable of one data type into another data type
Convert to string type
mode | explain | case |
---|---|---|
toString() | Convert to string | var num = 1; alert(num.toString()); |
String() | Convert to string | var num = 1; alert(String(num)); |
Plus concatenated string | And string splicing results are strings | var num = 1; alert(num + "hello"); |
- toString() and String() are used differently
- There are three conversion methods. The third plus splicing string conversion method is also called implicit conversion
Convert to numeric type (emphasis)
mode | explain | case |
---|---|---|
parseInt(String) | Converts a String type to an integer value | parseInt("12") |
parseFloat(String) | Convert String type to floating point numeric type | parseFloat("12.0") |
Number() | Cast String type to numeric type | Number("12") |
js implicit conversion (- * /) | Implicitly convert to numeric type by arithmetic operation | "12" - 0 |
Note the case of parseInt and parseFloat letters
Implicit conversion is our common conversion method
Convert to Boolean
mode | explain | case |
---|---|---|
Boolean() | Convert other types to Booleans | Boolean("true"); |
Values representing null and negative are converted to false; The rest are converted to true
5, Operator
Operators, also known as operators, are symbols used to realize the functions of assignment, comparison and arithmetic operation
1. Arithmetic operator
+(add), - (subtract), * (multiply), / (divide),% (take remainder)
console.log(1 + 1); console.log(1 - 1); console.log(1 * 2); console.log(2 / 1); console.log(5 % 3);
Floating point numbers are far less accurate than integers. Do not directly judge whether the operation results of two floating point numbers are equal
Expressions and return values
Expression: a combination of numbers, operators, variables, etc. in a meaningful arrangement that can obtain numerical values
The expression will eventually have a result, which will be returned to us, and we will become the return value
var num = 1 + 1; // Receive return value
Increment decrement operator
If you need to add or subtract 1 from a numeric variable repeatedly, you can use the increment (+) and decrement (- -) operators to do so
In JS, increment and decrement can be placed either before or after operators. When placed in front of a variable, we call it the pre increment operator, and when placed after a variable, we call it the post increment operator
Increment and decrement operators must be used with variables
Pre increment operator
var num = 10; ++num; console.log(num); // First add 1 and then return the value console.log(++num * 2); // 24
Post increment operator
var num = 10; num++; console.log(num); // Put back the value first, and then add 1 console.log(num++ * 2) // 22
Summary
Both pre increment and post increment operators can simplify the writing of code and make the value of variable + 1
When used alone, the running results are the same
When combined with other code, the execution result is different
- Post: assign value first and then calculate (add gradually later)
- Pre: operation before assignment (incremental addition first)
2. Logical operator
Concept: logical operator is an operator used for Boolean operation, and its return value is boolean type
operator | explain | case |
---|---|---|
&& | Logic and and | true && false |
|| | Logical or | true || false |
! | Logical not | ! true |
Short circuit operation ()
Principle of short circuit operation: when there are many expressions and the expression on the left can determine the result, the value of the expression on the right will not be calculated
Principle of short circuit operation: when there are many expressions and the expression on the left can determine the result, the value of the expression on the right will not be calculated
// Logic and short circuit operation returns expression 2 if the result of expression 1 is true, and expression 1 if expression 1 is false console.log(123 && 456); // Return to 456 console.log(0 && 1); // Return 0 console.log(0 && 1 + 2 && 456 + 123); // Return 0 // Logical or short circuit operation returns expression 1 if the result of expression 1 is true, and returns result expression 2 if the result of expression 1 is false console.log(123 || 456); // Return 123 console.log(0 || 1); // Return 1 console.log(0 || 1 + 2 || 456 + 123); // Return 2 // Logical interruption is very important. It will affect the expression of the running results of our program
Logic and short circuit operation returns expression 2 if the result of expression 1 is true, and expression 1 if expression 1 is false
Logical or short circuit operation returns expression 1 if the result of expression 1 is true, and returns result expression 2 if the result of expression 1 is false
Logical interruption is very important. It will affect the expression of the running results of our program
3. Comparison operator
Concept: the comparison operator is the operator used when comparing two data. After the comparison operation, a Boolean value will be returned as the result of the comparison operation
< (greater than), > (less than), < = (less than or equal to), > = (greater than or equal), = = (equal to)= (not equal to), = = = (congruent)== (incomplete)
==By default, the data type will be converted, and the string type will be converted to the number type
console.log(18 == "18"); // true console.log(18 != "18"); // false console.log(18 === "18"); // false
4. Assignment operator
Concept: an operator used to assign data to a variable
=(assignment), + = (plus equals), - = (minus equals), / = (divide equals), * = (multiply equals),% = (remainder equals)
5. Operator priority
The following table lists JavaScript operators from highest to lowest priority. Operators with the same priority are evaluated from left to right
operator | describe |
. [] () | Field access, array subscripts, function calls, and expression grouping |
++ -- - ~ ! delete new typeof void | Unary operator, return data type, object creation, undefined value |
* / % | Multiplication, division, modulo |
+ - + | Addition, subtraction, string concatenation |
<< >> >>> | displacement |
< <= > >= instanceof | Less than, less than or equal to, greater than, greater than or equal to, instanceof |
== != === !== | Equal, not equal, strict equality, non strict equality |
& | Bitwise AND |
^ | Bitwise XOR |
| | Bitwise OR |
&& | Logic and |
|| | Logical or |
?: | condition |
= oP= | Assignment, operation assignment |
, | multiple evaluation |
6, Process control
In the process of program execution, the execution order of each code has a direct impact on the result of the program. Many times, we need to control the execution order of the code to realize the functions we want to complete
Simple understanding: process control is to control the order in which our code is executed
There are three main structures of process control: sequence structure, branch structure and loop structure, which represent the order of code execution
1. Sequential structure
Sequential structure is the simplest and most basic process control in a program. It has no specific syntax structure. The program will execute in sequence according to the sequence of codes. Most codes in the program execute in this way
2. Branching structure
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 obtain different results
if statement
// if syntax structure /* if ( Conditional expression 1){ // Execute statement 1 } else if ( Conditional expression 2){ // Execute statement 2 } else { // Execute statement } */ // If the result of the if conditional expression is false, the statement in braces will not be executed and the code behind the if statement will be executed if (3 > 5) { alert("3 Greater than 5"); } else { alert("3 Less than 5"); }
Ternary expression
// Conditional expression? Expression 1: expression 2; // If the result of the conditional expression is true, the value of expression 1 is returned var num = 5; var result = if num > 5 ? "right" : "Unfortunately not" ; alert(result)
switch Statements
The 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 specific value options for variables, you can use switch
// The switch statement is also a multi branch structure, which can achieve the result of selecting one from many // Syntax structure switch transformation /* switch ((expression){ case value1: Execute statement 1; break; ··· default: Execute the last statement; }*/ // Code verification var num = parseInt(prompt("Please enter a number")); switch (num) { case 1: alert("Enter as one"); break; case 2: alert("The input is 2"); break; default: alert("Unrecognized"); }
When the value of num matches the value in case, it is a congruent relationship. It must be the same value and data type
If there is no break in the current case, the switch will not exit, but continue to execute the next case
difference
- In general, their two statements can be replaced with each other
- The switch ··· case statement usually deals with 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, while if ··· else statement has several conditions, it has to judge how many times
- When there are fewer branches, the efficiency of if ··· else statement is higher than that of switch statement; When there are many branches, the execution efficiency of switch statement is relatively high, and the structure is clear
3. Cyclic structure
The purpose of the loop: some statements can be executed repeatedly
for loop
In a program, a group of repeatedly executed statements is called the loop body. Whether it can continue to be executed repeatedly depends on the termination condition of the loop. The statement composed of the loop body and the termination condition of the loop is called a loop statement
for repeatedly executes some code, usually related to counting
/* Initialization variable is a common variable declared with var, which is usually used as my counter Is the conditional expression used to determine whether each loop continues to execute, that is, the termination condition The operation expression is the code executed at the end of each loop, which is often used to update (increment or decrement) our counter variables for (Initialize variables; Conditional expression; Operation expression){ Circulatory body } */ for (var i = 1; i < 101; i++) { console.log("This is a circular structure"); }
The for loop can execute different code repeatedly, mainly because the counter is used, and the counter will change during each loop
for (var i = 1; i <= 100; i++) { console.log("tom,this year" + i + "Years old"); }
Because of the existence of counters in the for loop, we can also repeat some operations, such as arithmetic operations
// Sum var sum = 0; for (var i = 1; i < 101; i++) { sum += i; } console.log("And are:" + sum); // Find the sum of numbers between 1 and 100 that can be divided by 3 var sum1 = 0; for (var i = 1; i <=100; i++) { if (i % 3 == 0) { sum1 += i; } } console.log(sum1);
for loop nesting
Loop nesting refers to defining the syntax structure of a loop statement in a loop statement
The outer loop circulates once, and the inner loop executes all
// Print multiplication formula table, inverted triangle var str_all = "" // Store the resulting value for (var i = 1; i <= 9; i++) { // Number of control rows for (var j = i; j <= 9; j++) { // Number of control columns str_all += i + "x" + j + "=" + i*j + "\t"; } str_all += "\n"; } console.log(str_all);
while Loop
while loop statement can execute the specified code in a loop on the premise that the conditional expression is true until the expression is not true
while ( Conditional expression ) { // Loop body code }
Implementation ideas
- Execute the conditional expression first. If the result is true, execute the loop code; If false, exit the loop and execute the following code
- Execute loop body code
- After the loop body code is executed, the program will continue to judge the execution condition expression. If the condition is still true, the loop body will continue to be executed until the loop condition is false
var str = "", num = 1; while (num <= 100 ) { num++; str += "How do you do\n"; } console.log(str); // Multiplication formula table var str = "", row = 1; while (row <= 9) { var col = 1; while (col <= row) { str += row + "x" + col + "=" + col*row + "\t"; col++; } row++; str += "\n"; } console.log(str);
do ··· while loop
The do... While statement is actually a variant of the while statement. The loop will execute the code block once, and then judge the conditional expression. If the condition is true, the loop body will be executed repeatedly, otherwise exit the loop
do { // Circulatory body } while ( Conditional expression )
Implementation ideas
- The difference from while is that do... While executes the loop body once before judging the conditions
4. continue and break
The continue keyword is used to immediately jump out of this loop and continue the next loop (the code after continue in this loop will be executed less than once)
The break keyword is used to immediately jump out of the entire loop (the end of the loop)
7, Array element
1. Array concept
The concept of array: using array can store a group of related data together and provide convenient access. An array is a collection of data, each of which is called an element. Any type of element can be stored in the array. Arrays are an elegant way to store a set of data under a single variable name
// Common variable var num = 10; // Arrays can store multiple values at a time var arr = [1, 2, 3, 4, 5];
2. Create array
-
Using the new keyword to create an array
var Array name = new Array(); var arr = new Array(); // Create a new array
-
Creating arrays using array literals
// 1. Create an empty array using array literals var Array name = []; // 2. Create an array with an initial value using array literal var Array name = ["Xiaobai", "Xiao Hei", 2, true];
The data in the array must be separated by commas
3. Access array
Index of array
Index (subscript): the ordinal number used to access array elements (the array subscript starts from 0)
The array can access, set and modify the corresponding array elements through the index. We can obtain the elements in the array in the form of "array name [index]"
var arr = ["Xiaobai", "Xiao Hei", 2, true]; console.log(arr[0]);
Traversal array
for (var i = 0; i < 4; i++) { console.log(arr[i]); }
Because our array index numbers start at 0, i must start at 0, i < 4
When outputting, the ARR [i] I counter is used as an index number
Array length
Length gets the length of the array
for (var i = 0; i < arr.length; i++) { // Dynamically detect the number of elements in the array console.log(arr[i]); }
New element
You can add array elements by modifying the length of length and index number
-
The purpose of array expansion can be achieved by modifying the size of length
-
length is readable and writable
arr.length = 5; // Manually modify the length of the array to 5. There should be 5 elements in the array // The default value added is undefined
-
-
Add an array element by modifying the array index number
-
You can append array elements by modifying the array index number
var arr1 = ["Xiaobai", "Xiao Hei", 2, true]; arr1[4] = 5; console.log(arr1.length); // Append an element // If the index number already has a value, the original array element is replaced
Do not directly assign values to array elements, otherwise the array elements inside will be overwritten
var arr = [2, 0, 6, 80, 56, 56, 0] // The number greater than 50 in the array is required to be stored in the new array var new_arr = []; // The index of the initial array is 0 for (var i = 0; i < arr.length; i++) { if (arr[i] > 50) { // The index number of the new array starts from 0 and increases in sequence new_arr[neww_arr.length] = arr[i]; } }
-
4. Array sorting
Bubble sorting
- An algorithm that displays a series of data in a certain order (from small to large or from large to small)
var arr = [1, 5, 0, 6, 66, 9, 564, 1212, 12] // Sort the array in ascending order for (var i = 0; i < arr.length-1; i++) { for (var j = 0; j < arr.length - 1 - i; j++) { if (arr[j] > arr[j+1]) { var temp = arr[j]; // Temporary storage variable arr[j] = arr[j+1]; arr[j+1] = temp; } } } console.log(arr);