preface
If you want to do well, you must first sharpen your tools. In order to improve development efficiency, VScode is selected.
-
Management - Settings - common settings - font Consolas, 'Microsoft YaHei Light', monospace
-
Chinese vscade
-
Prettier formatting code (indented 2 cells)
-
Auto Rename Tag synchronously modifies tags
-
CSS support for HTML documents
-
HTML Snippets automatically enter Html tags
-
JavaScript (ES6) code snippets6 syntax support
-
open in browser
Fundamentals of programming
"Computer language" is divided into machine language, assembly language and high-level language. The final execution inside the computer is machine language, which is composed of binary numbers such as 0 and 1.
"Data storage unit" 8bit (bit) = 1B(Byte) bytes kilobytes 1KB = 1024B
The program written in the "translator" high-level language cannot be recognized by the computer. It needs to be converted to translate the source code program into machine language before it can run. The js interpreter in the browser is such a translator.
"Program running"
-
When opening a program, first load the program code from the hard disk into memory
-
The CPU executes code in memory
-
Note: an important reason for using memory is that the cpu runs too fast. If you only read data from the hard disk, you will waste cpu performance. Therefore, you use memory with faster access speed to save running data. (memory is electric, hard disk is mechanical)
1, New JavaScript
Brendan EICH, the "founder", was originally named LiveScript and later renamed JavaScript in cooperation with Sun.
"JavaScript" is a script language running on the client side. It does not need to be compiled and is interpreted and executed line by line by js interpreter (js engine). Node.js can also be used for server-side programming.
1. Function of JavaScript
-
Form dynamic verification (password strength detection)
-
Web effects
-
Server development (Node.js)
-
Desktop program (Electron), App(Cordova), control hardware - Internet of things (Ruff), game development (cocos2d JS)
2. Introduction to browser executing JS
The browser is divided into two parts: rendering engine and JS engine
Rendering engine: it is used to parse HTML and CSS, commonly known as kernel, such as blink of chrome browser and webkit of old version
JS engine: also known as JS interpreter. It is used to read the JavaScript code in the web page and run it after processing, such as V8 of chrome browser
The browser itself does not execute JS code, but executes JS code through the built-in JavaScript 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, JavaScript language is classified as script language and will be interpreted and executed line by line.
3. Composition of JS
"JavaScript composition" ECMAScript(JavaScript syntax), DOM (document object model), BOM (browser object model)
ECMAScript: ECMAScript specifies the programming syntax and basic core knowledge of JS. It is a set of JS syntax industry standards jointly followed by all browser manufacturers.
Document Object Model (DOM) is a standard programming interface recommended by W3C organization to deal with extensible markup language. Through the interface provided by Dom, various elements on the page can be operated (size, position, color, etc.).
BOM (Browser Object Model) refers to the browser object model. It provides an object structure that is independent of content and can interact with the browser window. Through BOM, you can operate the browser window, such as pop-up box, control browser jump, obtain resolution, etc.
4.2 writing position
JS has three writing positions: in line, embedded and external.
Inline
<input type="button" value="Let me try" onclick="alert('Hello World')" />
Embedded
<script> alert('Hello World~!'); </script>
External type
Reference external js file <script src = "my.js"></script>
"Notes"
Single-Line Comments
//I am a single line comment (shortcut key: ctrl + /)
multiline comment
/* Get user age and name And displayed through the prompt box Click management - Keyboard Shortcuts - switch block notes in the lower left corner of vscode (The default shortcut key (alt + shift + a) is changed to (ctrl + shift + /) */
6.JavaScript input and output statements
<script> // This is an input box prompt('Please enter your age'); // The output of the alert pop-up box is displayed to the user alert('The result of the calculation is'); // Console console output to programmer for testing console.log('I'm what programmers can see'); </script>
Note: alert() is mainly used to display messages to users, console Log () is used to show the runtime messages to the programmer.
7. Code specification
1. Identifier naming specification
-The naming of variables and functions must be meaningful
-Variable names are generally nouns
-The names of functions are usually verbs
2. Operator specification
// Leave a space on the left and right sides of the operator for (var i = 1; i <= 5; i++) { if (i == 3) { break; // Directly exit the whole for loop and jump to the statement below the whole for loop } console.log('I'm eating the third' + i + 'Where's a steamed stuffed bun'); }
3. Single line note specification
for (var i = 1; i <= 5; i++) { if (i == 3) { break; // Notice a space in front of a single line comment } console.log('I'm eating the third' + i + 'Where's a steamed stuffed bun'); }
4. Other specifications
//Keyword operator space if (true) {} for (var i = 0; i<=10; i++) {}
2, Variable
1. Concept of variable
"Variable" is a space for storing data requested by the program in memory. Variables are containers for storing data. You can obtain data or even modify data through variable names.
2. Use of variables
"1. Declare variables"
// 1. Declare variable var num; //Declare a variable named {num}
var is a JS keyword used to declare variables (the meaning of variable). num is the variable name defined by us. You can access the allocated space in memory through the variable name.
"2. Assignment"
num = 10;//Assign a value of , 10 to the , num , variable
"3. Initialization of variables"
Declaring and assigning a variable is called variable initialization.
var num = 10;//Declare the variable and assign a value of 10
"4. Variable syntax extension"
// 1. After a variable is re assigned, its original value will be overwritten, and the variable value shall be subject to the last assigned value. var num = 10; num = 11; // 2. Declare multiple variables at the same time (just write a var and separate multiple variable names with English commas) var num = 10, age = 15, name = 'fan';
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); | Do not declare, only assign | 10 |
"5. Variable naming specification"
3. Keywords and reserved words
"Identifier" refers to the name obtained by the developer for variables, attributes, functions and parameters. Identifiers cannot be keywords or reserved words.
"Keywords" refer to the words already used by JS itself. They can no longer be used as variable names and method names
Including: 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, etc.
"Reserved words" are actually 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.
boolean, byte, char, class, const, debugger, double, enum, export, extends, decimal, float, goto, implements, import, int, interface, long, automatic, package, private, protected, public, short, static, super, synchronized, throws, transient, volatile, etc.
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.
3, Data type
There are two types: simple data types (Number,String,Boolean,Undefined,Null) and complex data types (objects).
The variable data type of js is determined according to the value to the right of the equal sign only when the program is running
// js is a dynamic language variable, and the data type can be changed var x = 10; // x is numeric x = 'pink'; // x string type
Simple data type | explain | Default value |
---|---|---|
Number | Numeric type, including integer and floating-point values | 0 |
String | String type | "" |
Boolean | Boolean Boolean | false |
Undefined | var a; The variable a is declared but not assigned. In this case, a = undefined | undefined |
Null | var a = null; Declared that variable a is null | null |
1.Number digital type
"Numeric base"
// 1. In JS, 0 is added before octal and 0x is added before hexadecimal var num1 = 07; //Corresponding to decimal 7 // 2. Hexadecimal digit sequence range: 0 ~ 9 and A~F var num = 0xA;
The values in the numeric range JavaScript have maximum and minimum values
-
Maximum value: number MAX_ Value: 1.7976931348623157e+308
-
Minimum value: number MIN_ Value, value: 5e-32
-
Special value: Infinity infinity - Infinity infinitesimal NaN represents a non number
-
isNaN(): used to determine whether a variable is of non numeric type. The non numeric type is true and the numeric type is false.
2.String type
// 1. The string type can be any text in quotation marks, and the syntax is single quotation marks and double quotation marks var msg = 'My name is'; var name = "fan";
"1. String escape characters" start with \, as follows: 👇👇
Escape character | explain |
---|---|
\n | Newline, n means newline |
\\ | Inclined rod\ |
\' | Single quotation mark‘ |
\" | Double quotation mark“ |
\t | tab indent |
\b | b means blank |
"2. String length"
A string is composed of several characters. The number of these characters is the length of the string.
// 1. The string type can be any text in quotation marks, and the syntax is single quotation marks and double quotation marks var msg = 'I'm a handsome rice boss'; console.log(msg.length); //Display 8
"3. String splicing"
Multiple strings can be spliced with + in the form of string + any type = new string after splicing.
Before splicing, any type added to the string will be converted into a string, and then spliced into a new string
//1.1} string "addition" alert('hello' + ' ' + 'world'); // hello world //1.2} numeric string "addition" alert('100' + '100'); // 100100 //1.3 ■ numeric string + numeric value alert('11' + 12); // Formula 1112 +: numerical values are added and characters are connected //1.4} string splicing reinforcement var age = 18; alert("Rice boss this year" + age +"Years old");
3. Boolean
Boolean types have two values: true and false, where true represents true (true) and false represents false (false).
When Boolean and numeric types are added, the value of true is 1 and the value of false is 0.
console.log(true + 1) // 2 console.log(false + 1) // 1
4.Undefined and Null
If a variable is declared without assignment, there will be a default value undefined (if connected or added, pay attention to the result 😊)
var variable; console.log(variable); // undefined console.log("Hello" + variable); //Hello, undefined console.log(11 + variable); // NaN console.log(true + variable);// NaN
A variable is declared and assigned null, and the stored value is null
var var2 = null; console.log(var2); // null console.log("Hello" + var2); //Hello, null console.log(11 + var2); // 11 console.log(true + var2);// 1
5. Get variable type and conversion
1. Test the data type of the variable
var num = 10; console.log(typeof num)//The result is number
2. Literal quantity
Is the representation of a fixed value in the source code, that is, how to express this value by literal quantity. The type of data can be determined by the format characteristics of the data
-
-
Number literal: 8,9,10
-
String literal: 'rice boss',' front-end development '
-
Boolean literal: true,false
-
3. Data type conversion
-
Convert to string
mode | explain | case |
---|---|---|
toString() | Convert to string | var num=1; alert(num.toString()) |
String() | Force conversion | var num=1; alert(String(num)) |
Plus concatenated string | And string splicing results are strings | var num=1; alert(num + 'I am a string') |
<script> // 1. Convert numeric variables to string variables toString() var num = 10; var str = num.toString(); console.log(str); console.log(typeof str); // 2. We use string (variable) console.log(String(num)); // 3. Use the method of + splicing string to realize the implicit conversion of conversion effect console.log(num + ''); </script>
-
Convert to numeric
mode | explain | case |
---|---|---|
parseInt(String) function | Convert string type to integer type | parseInt('11') |
parseFloat(String) function | Convert string type to floating point type | parseFloat('11.2') |
Number() cast function | Cast string type to numeric type | Number('12') |
js implicit conversion (- * /) | Implicit conversion to numerical type by arithmetic operation | '12' - 0 |
<script> // var age = prompt('Please enter your age '); // 1. ParseInt (variable) can convert character type to number type to get integer // console.log(parseInt(age)); console.log(parseInt('3.14')); // 3 rounding console.log(parseInt('3.94')); // 3 rounding console.log(parseInt('120px')); // 120 will go to this px unit console.log(parseInt('rem120px')); // NaN // 2. Parsefloat (variable) can convert character type to number type to get decimal floating point number console.log(parseFloat('3.14')); // 3.14 console.log(parseFloat('120px')); // 120 will remove this px unit console.log(parseFloat('rem120px')); // NaN // 3. Use number (variable) var str = '123'; console.log(Number(str)); console.log(Number('12')); // 4. Arithmetic operation - * / implicit conversion is used console.log('12' - 0); // 12 console.log('123' - '120'); console.log('123' * 1); </script>
-
If it is converted to Boolean, the values representing null and negative will be converted to false, such as' ', 0, NaN, null, undefined, and other values will be converted to true
mode | explain | case |
---|---|---|
Boolean() | Convert other types to Booleans | Boolean('true') |
<script> 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('------------------------------'); console.log(Boolean('123')); console.log(Boolean('how are you')); console.log(Boolean('I'm fine')); </script>
4, Operator
1. Operator (operator)
"Operator" is a symbol used to realize the functions of assignment, comparison and arithmetic operation. Common operators are classified as follows 👇
-
Arithmetic operator
-
Increment and decrement operators
-
Comparison operator
-
Logical operator
-
Assignment Operators
"1. Arithmetic operator"
operator | describe | case |
---|---|---|
+ | plus | 10+20=30 |
- | reduce | 10-20=-10 |
* | ride | 10*20=200 |
/ | except | 10/20=0.5 |
% | Surplus (mold taking) | Returns the remainder of division 9% 2 = 1 |
-
Precision of floating point numbers
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
-
-
The highest precision of floating-point numbers is 17 decimal places, but its precision is far less than that of integers, so don't directly judge whether two floating-point numbers are equal!
-
-
Expressions and return values
-
-
Expression: an expression consisting of numbers, operators, and variables.
-
Return value: each expression will have a final result after corresponding operation, which is called the return value of the expression
-
"2. Increment and decrement operators"
Increment and decrement operators must be used with variables.
-
Increment operator
var num = 10; alert(++num + 10); // 21 use the formula: add it first, and then return the value var num1 = 10; alert(10 + num1++); // 20. Use the formula: first return the original value, and then add it by yourself
var num = 1; var num2 = ++num + num++; //num = 2 console.log(num2);//4 var num = 1; var num1 = 1; var num2 = num++ + num1++; // 1 + 1 console.log(num2);//2 var num = 1; var num2 = num++ + num++;// 1 + 2 console.log(num2); // 3
"3. Comparison operator"
operator | describe | case | result |
---|---|---|---|
< | Less than sign | 1<2 | true |
> | Greater than sign | 1>2 | false |
>= | Greater than or equal to sign (greater than or equal to) | 2 >= 2 | true |
<= | Less than or equal to sign (less than or equal to) | 3 <= 2 | false |
== | Equal sign (transformation) | 15 == '15' | true |
!= | Unequal sign | 37 != 37 | false |
=== !=== | Congruent and unequal (required values and data types are consistent) | 37 === '37' | false |
"4. Logical operators"
Logical operators are operators used for Boolean operations
Short circuit operation: when there are multiple expressions (values) and the expression value on the left can determine the result, the operation of the expression value on the right will not be continued;
operator | describe | case | characteristic |
---|---|---|---|
&& | "Logical and" is abbreviated as "and" | true && false | True is returned only when both sides are true |
|| | "Logical or", or "or" for short | true | Is it true |
! | "Logical not", abbreviated as "not" | !true | Reverse |
"5. Assignment operator"
operator | describe | case |
---|---|---|
= | Direct assignment | var userName = 'fan' |
+= -= | Add or subtract a number before assigning a value | var age=5; age+=5 |
*= /= %= | Assign value after multiplication, division and modulus | var age=5; age*=5 |
"6. Operator priority"
priority | operator | order |
---|---|---|
1 | parentheses | () |
2 | Unary operator | ! ++ -- |
3 | Arithmetic operator | First * /% then +- |
4 | Relational operator | > >= < <= |
5 | Equality operator | == != === !== |
6 | Logical operator | First & & then|| |
7 | Assignment Operators | = |
8 | Comma Operator | , |
5, Branch process control
"1. Process control"
In the process of a 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. 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.
"2. Branch process control"
// 1. Code statement executed when the condition is satisfied if (Conditional expression) { } // 2.if # else # statement if (Conditional expression) { //[if] the condition is true, the code to be executed } else { //[otherwise] executed code } // 3. 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 }
"3. Ternary expression"
//If expression 1 is true, the value of expression 2 is returned; if expression 1 is false, the value of expression 3 is returned Expression 1 ? Expression 2 : Expression 3;
"4.switch branch process control"
It 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: //The code to execute when the expression , is equal to , value2 , break; default: //Code to be executed when the expression , is not equal to any , value , }
6, Circulation
1. for loop
operator | describe |
---|---|
initialize variable | It is usually used to initialize a counter. The expression can declare a new variable using the var keyword, which helps us record the number of times. |
Conditional expression | Used to determine whether each loop can be executed. If the result is true, continue the loop, otherwise exit the loop |
Operation expression | The expression to be executed at the end of each loop. Typically used to update the value of a counter variable |
for(initialize variable; Conditional expression; Operation expression ){ //Circulatory body }
"Execution process"
-
Initialize variables. The initialization operation will be executed only once in the whole for loop.
-
Execute the conditional expression. If true, execute the loop body statement. Otherwise, exit the loop and the loop ends.
-
Execute the operation expression, and the first round ends.
-
At the beginning of the second round, execute the conditional expression directly (no longer initializing variables). If it is true, execute the loop body statement, otherwise exit the loop.
-
Continue to execute the operation expression, and the second round ends
<script> // The for loop can execute the same code for (var i = 1; i <= 10; i++) { console.log('Daughter in law, I was wrong'); } // We can let the user control the number of outputs var num = prompt('Please enter the number of times'); for (var i = 1; i <= num; i++) { console.log('Daughter in law, I was wrong'); } </script>
<script> // The for loop can execute different codes repeatedly, because we have the existence of counter variable i, and the value of i will change every time // We want to output a person 1 ~ 100 years old // for (var i = 1; i <= 100; i++) { // console.log('This person is' + i + 'years old'); // } for (var i = 1; i <= 100; i++) { if (i == 1) { console.log('This man is one year old. He was born'); } else if (i == 100) { console.log('This man is 100 years old. He's dead'); } else { console.log('This man this year' + i + 'Years old'); } } </script>
<script> // The for loop repeats some operations. For example, we do 100 addition operations // Find the cumulative sum of integers between 1 and 100 // We need to cycle 100 times and we need a counter i // We need a variable sum to store the results, but the initial value must be 0 // Core algorithm: 1 + 2 + 3 + 4, sum = sum + i; var sum = 0; // Summation variable for (var i = 1; i <= 100; i++) { // sum = sum + i; sum += i; } console.log(sum); </script>
2. Breakpoint debugging
Breakpoint debugging refers to setting a breakpoint on a certain line of the program. When debugging, the program will stop running to this line, and then you can debug step by step. During debugging, you can see the current value of each variable. If there is an error, the error will be displayed when debugging to the wrong code line, and stop.
Breakpoint debugging can help us observe the running process of the program
Press F12 -- > sources -- > in the browser to find the file to be debugged -- > set a breakpoint on a line of the program
Watch: monitoring. You can monitor the change of variable value through watch. It is very common.
F11: the program executes step by step. Let the program execute line by line. At this time, observe the change of the value of the variable in the watch.
The ability of code debugging is very important. Only when you learn code debugging can you learn your ability to solve bugs. Beginners should not stop debugging if they find it troublesome to debug the code. They will certainly learn it if they spend some time on knowledge, but they will never learn it if they don't practice it.
3. Double for loop
Loop nesting refers to defining the syntax structure of a loop statement in a loop statement. For example, a for loop can be nested in a for loop statement. Such a for loop statement is called double for loop.
for (Initial of external circulation; Conditions of external circulation; Operation expression of outer loop) { for (Initial of internal circulation; Conditions of internal circulation; Inner loop operation expression) { Code to execute; } } //for loop printing 99 multiplication table var str = ""; for (var i = 1; i <= 9; i++) { for (var j = 1; j <= i; j++) { str += j + "x" + i + "=" + j * i + "\t"; } str += "\n"; } console.log(str);
Case analysis
① There are 9 lines in total, but the number of each line is different, so a double for loop is required
② The for loop of the outer layer controls the number of lines i, which can be printed 9 times. ③ the for loop of the inner layer controls the formula j of each line
④ Core algorithm: the number of formulas in each line is exactly the same as the number of lines, J < = I;
⑤ After each line is printed, you need to change another line ⑥ replace the formula with i and j
<script> // Print five rows and five columns of stars var str = ''; for (var i = 1; i <= 5; i++) { // The outer loop is responsible for printing five lines for (var j = 1; j <= 5; j++) { // The inner circle is responsible for printing five stars in a row str = str + '★'; } // If one line is printed, 5 stars will be added on another line \ n str = str + '\n'; } console.log(str); </script>
<script> // Print n rows and N columns of stars var rows = prompt('Please enter the number of rows:'); var cols = prompt('Please enter the number of columns:'); var str = ''; for (var i = 1; i <= rows; i++) { for (var j = 1; j <= cols; j++) { str = str + '★'; } str += '\n'; } console.log(str); </script>
4. while loop
while (Conditional expression) { //Loop body code } // 1. Execute the conditional expression first. If the result is true, execute the loop body code; //If false, exit the loop and execute the following code // 2. Execute loop body code // 3. After the loop body code is executed, the program will continue to judge the execution condition expression,
Note:
① When using a while loop, you must pay attention to that it must have exit conditions, otherwise it will become an endless loop
② The difference between the while loop and the for loop is that the while loop can judge more complex conditions, such as user name and password
//Calculate the cumulative sum of 1-100 var i = 1; var sum = 0; while (i <= 100) { sum += i; i++; } console.log(sum);
5. Do while loop
do { //Loop body code - the loop body code is executed repeatedly when the condition expression is true } while(Conditional expression); //Execute the loop body code once before executing the conditional expression //Calculate the even cumulative sum within 100 var i = 1; var sum = 0; do { if (i % 2 == 0) { sum += i; } i++; } while (i <= 100); console.log(sum);
6. continue break
The continue keyword is used to immediately jump out of this loop and continue the next loop (the code after continue in the body of this loop will be executed less than once).
// Continue keyword exit this time (the current cycle) and continue to execute the remaining cycles for (var i = 1; i <= 5; i++) { if (i == 3) { continue; // As long as you meet continue, exit this cycle and jump directly to i++ } console.log('I'm eating the third' + i + 'A steamed stuffed bun'); }
The break keyword is used to immediately jump out of the entire loop (the end of the loop).
<script> // break exits the entire loop for (var i = 1; i <= 5; i++) { if (i == 3) { break; } console.log('I'm eating the third' + i + 'A steamed stuffed bun'); } </script>
7, Array
"1. Concept of array"
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.
"2. Create array"
-
Use the new keyword to create an array;
var Array name = new Array([n]);//[] stands for optional. If n is written, it stands for the length of the array var arr = new Array();//An empty array named {arr} was created
-
Creating arrays with array literals
// 1. Create an empty array using array literals var Array name = [];//If n is written, it represents the length of the array //2. Create an array with initial value using array literal //3. Declaring an array and assigning values is called array initialization var arr =['1','2','3','4']; var arr2 = ['fan',true,17.5];//Any type of data can be stored in the array
"3. Access array elements"
Index (subscript): the ordinal number used to access array elements. Index starts at 0
//Define array var arrStus = [1,2,3]; //Gets the second element in the array alert(arrStus[1]); //If there is no element corresponding to the index value when accessing the array (the array is out of bounds), //The return value is undefined
"4. Traversal array"
The elements in the array are accessed once from beginning to end.
//The length of the array is equal to the number of elements by default //When the elements in our array change, the length attribute changes together //If the set length attribute value is greater than the number of elements in the array, a blank element will appear at the end of the array; //If the set length attribute value is less than the number of elements of the array, the array elements exceeding this value will be deleted var arr = ["red", "blue", "green"]; for (var i = 0; i < arr.length; i++) { console.log(arr[i]); } arr.length = 2; console.log(arr);// red blue
"4. New element in array"
In the array, you can insert new elements at the end of the array in the following ways;
// 1. Array [array. length] = new data; arr = [] //arr.length = 0; for (var i = 0; i < 10; i++) { arr[arr.length] = '0'; } console.log(arr);
"5. New element in array"
In the array, you can insert new elements at the end of the array in the following ways;
// 1. Array [array. length] = new data; arr = [] //arr.length = 0; for (var i = 0; i < 10; i++) { arr[arr.length] = '0'; } console.log(arr);
"6. Cases"
// 1. Filter the elements of the array {greater than 10, select them and put them in the new array var arr = [2, 0, 6, 1, 77, 0, 52, 0, 25, 7]; var newArr = []; var j = 0; for (var i = 0;i < arr.length; i++){ if (arr[i] >= 10) { newArr[j] = arr[i]; j++; } } console.log(newArr); //The second method} takes advantage of the variability of array length for (var i = 0;i < arr.length; i++){ if (arr[i] >= 10) { newArr[j] = arr[i]; j++; } }
// 2. Flip array //Take the 4th index number of the old array (arr.length - 1) and give the 0th element of the new array index number (newArr.length) //We take a , decreasing approach , i-- var arr = ['red', 'green', 'blue', 'pink', 'purple']; var newArr = []; for(var i = arr.length - 1; i >= 0;i--) { newArr[newArr.length] = arr[i] } console.log(newArr);
// 3. Array converted to string |, split with "|" or other symbols //A new variable is required to store the converted String str //Traversal takes out data, adds it to str, and then adds a separator var arr = ['red', 'green', 'blue', 'pink', 'purple']; var str = ''; for(var i = 0; i < arr.length; i++) { str += arr[i] + '|'; } console.log(str);
// 4. Array converted to string |, split with "|" or other symbols //A new variable is required to store the converted String str //Traversal takes out data, adds it to str, and then adds a separator var arr = ['red', 'green', 'blue', 'pink', 'purple']; var str = ''; for(var i = 0; i < arr.length; i++) { str += arr[i] + '|'; } console.log(str);
"7. Bubble sorting"
function sort(arr) { 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]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } return arr; } var arr1 = sort([1,4,2,9]); console.log(arr1);//1 2 4 9
8, Functions
"1. Concept of function"
It encapsulates a code block that can be repeatedly called and executed, and a large amount of code can be reused through functions. A function is a data type.
"2. Use of functions"
-
Declarative function
8, Functions
"1. Concept of function"
It encapsulates a code block that can be repeatedly called and executed, and a large amount of code can be reused through functions. A function is a data type.
"2. Use of functions"
-
Declarative function
1. adopt function Keyword definition function -- Named function function Function name() { //Function body code } //1.1 , function , is the keyword to declare a function, which must be lowercase //1.2 , function name , named as verb form , example: getSum 2. Defining functions through function expressions ---Anonymous function var fn = function() {}; //2.1 fn is a variable name, not a function name //2.2 fn is a variable, but the variable stores a function //2.3 the function created by function expression can be created by variable name (); To call // 2.4 function expressions can also define formal parameters and call incoming arguments.
The second way to use anonymous functions--Anonymous function self call (function(){ alert(123); })();
-
Call function
Function name();//After the function declaration, the function code is executed.
-
Encapsulation of functions
-
Function encapsulation is to encapsulate one or more functions through functions, and only provide a simple function interface.
-
/* For example, use the encapsulation function to calculate the 1-100 cumulative sum */ function getSum() { var sumNum = 0; //Prepare a variable and save the cumulative sum for (var i = 1; i <= 100; i++) { sumNum += i; //Add each value to the variable } alert(sumNum); } //Call function getSum();
"3. Function parameters"
-
Formal parameters: parameters passed during function definition (actual parameter values are passed to formal parameters, and variables are not declared)
-
Argument: parameter passed during function call
//Function declaration with arguments function Function name(Formal parameter 1,Formal parameter 2,Formal parameter 3...) { //Function body } //Function call with arguments Function name(Argument 1,Argument 2,Argument 3...); // Function call with arguments Function name(Argument 1,Argument 2,Argument 3...); // Inside the parentheses of the function call are the arguments (actual parameters) Attention (1) Multiple parameters are separated by commas (2) Formal parameters can be regarded as undeclared variables
-
"When the number of function parameters and arguments does not match"
Number of parameters | explain |
---|---|
The number of arguments is equal to the number of formal parameters | Output correct results |
The number of arguments is more than the number of formal parameters | Only get the number of formal parameters |
The number of arguments is less than the formal parameter | Multiple formal parameters are defined as undefined and the result is NaN |
function getSum(a, b, c) { return a + b + c; } // The default value of the formal parameter in js is undefined. //Call function var n = getSum(1, 2);// n = NaN var n = getSum(1, 2, 3, 4); //1 + 2 +3 = 6
"4. Return value of function"
Return value: the data represented by the function call as a whole; After the function is executed, you can return the specified data through the return statement.
//1. Declaration function function Function name() { ... return Value to return; // 1. When the function encounters return, it will stop executing and return the specified value // 1. If the function does not return, the returned value is undefined } //Call function Function name(); //At this point, you can call the function to get the return value in the function body
//2. Return value format of function // Function function name (){ // return the result to be returned; // } // Function name (); // (1) Our function only implements a certain function. The final result needs to be returned to the caller of the function. The function name () is realized through return // (2) As long as the function encounters a return, it will return the following results to the caller of the function. Function name () = the results after return // 3. Code verification function getResult() { return 666; } getResult(); // getResult() = 666 console.log(getResult());
<script> // Use the function to find the maximum value in the array [5,2,99101,67,77]. function getArrMax(arr) { // Arr accepts an array arr = [5,2,99101,67,77] var max = arr[0]; for (var i = 1; i <= arr.length; i++) { if (arr[i] > max) { max = arr[i]; } } return max; } // getArrMax([5, 2, 99, 101, 67, 77]); // The argument is an array // In our actual development, we often use a variable to accept the return result of the function, which is easier to use // var re = getArrMax([5, 2, 99, 101, 67, 77]); var re = getArrMax([3, 77, 44, 99, 143]); console.log(re); </script>
"5. Precautions for function return value"
// Function return value considerations // 1. return stop function function getSum(num1, num2) { return num1 + num2; // The code after return will not be executed alert('I won't be executed!') } console.log(getSum(1, 2)); // 2. return can only return one value function fn(num1, num2) { return num1, num2; // The result returned is the last value } console.log(fn(1, 2));
// 3. We find the result of addition and subtraction multipliers of any two numbers function getResult(num1, num2) { return [num1 + num2, num1 - num2, num1 * num2, num1 / num2]; } var re = getResult(1, 2); // Returns an array console.log(re); // 4. If our function has a return, it returns the value after the return. If the function does not have a return, it returns undefined function fun1() { return 666; } console.log(fun1()); // Return to 666 function fun2() { } console.log(fun2()); // The result returned by the function is undefined
"6. The difference between break, continue and return"
-
break: end the current loop body (e.g. for, while)
-
Continue: jump out of this cycle and continue to execute the next cycle
-
Return: it can not only exit the loop (in the function body), but also return the value in the return statement. At the same time, it can also end the code in the current function body
//Avoid stepping on the hole. return can only end the code in the function body function breakDown() { for (var i = 0; i < 10; i++) { if (i == 5) { return 1; } console.log(i); } } breakDown(); //Avoid stepping on the pit 2. If the function has a return, it returns the value after the return; // return d,a,b; Returns the value of B //If the function does not have a return statement, it returns undefined
"7. Use of arguments"
When you are not sure how many parameters are passed, you can use arguments to get them. In JS, arguments is actually a built-in object of the current function. All functions have a built-in arguments object in which all arguments passed are stored. Arguments is displayed as a pseudo array, so it can be traversed.
-
Pseudo arrays have the following characteristics:
-
With length attribute
-
Store data by index
-
push, pop and other methods without array
-
<script> // The use of arguments only functions have arguments objects, and each function has built-in arguments function fn() { // console.log(arguments); // It stores all the passed arguments arguments = [1,2,3] // console.log(arguments.length); // console.log(arguments[2]); // We can iterate through arguments as an array for (var i = 0; i < arguments.length; i++) { console.log(arguments[i]); } } fn(1, 2, 3); fn(1, 2, 3, 4, 5); // Pseudo arrays are not real arrays // 1. Have the length attribute of the array // 2. Stored by index // 3. It doesn't have some methods of real array, such as pop() push(), etc </script>
//Using pseudo array {to find the maximum value function getMax() { var max = arguments[0]; for (var i = 1; i < arguments.length; i++) { if (arguments[i] > arguments[0]) { max = arguments[i]; } } return max; } var result = getMax(1,3,77,5,85) colsole.log(result);
"8. Case"
1. Use the function to flip any array
<script> // Flip any array with function reverse flip function reverse(arr) { var newArr = []; for (var i = arr.length - 1; i >= 0; i--) { newArr[newArr.length] = arr[i]; } return newArr; } var arr1 = reverse([1, 3, 4, 6, 9]); console.log(arr1); var arr2 = reverse(['red', 'pink', 'blue']); console.log(arr2); </script>
2. Bubble sorting by function
<script> // Using function bubble sort sort sort function sort(arr) { for (var i = 0; i < arr.length - 1; i++) { for (var j = 0; j < arr.length - i - 1; j++) { if (arr[j] > arr[j + 1]) { var temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } return arr; } var arr1 = sort([1, 4, 2, 9]); console.log(arr1); var arr2 = sort([11, 7, 22, 999]); console.log(arr2); </script>
3. Use function to judge leap year
<script> // Using function to judge leap year function isRunYear(year) { // If it is a leap year, we return true; otherwise, we return false var flag = false; if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) { flag = true; } return flag; } console.log(isRunYear(2000)); console.log(isRunYear(1999)); </script>
4. Functions can be called to each other
function fn1() { console.log(111); fn2(); console.log('fn1'); } function fn2() { console.log(222); console.log('fn2'); } fn1();
5. The user inputs the year and outputs the number of days in February of the current year
<script> // The user inputs the year and outputs the number of days in February of the current year function backDay() { var year = prompt('Please enter the year:'); if (isRunYear(year)) { // Calling a function requires parentheses alert('The current year is a leap year. February has 29 days'); } else { alert('The current year is a normal year. February has 28 days'); } } backDay();
// Function to determine whether it is a leap year function isRunYear(year) { // If it is a leap year, we return true; otherwise, we return false var flag = false; if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) { flag = true; } return flag; } </script>
"8. Two declaration methods of function"
// How functions are declared // 1. Use function keywords to customize functions (named functions) function fn() { } fn();
// 2. Function expression (anonymous function) // var variable name = function() {}; var fun = function(aru) { console.log('I'm a function expression'); console.log(aru); } fun('pink teacher'); // (1) fun is a variable name, not a function name // (2) The declaration method of function expression is similar to that of variable declaration, except that the value is stored in the variable and the function is stored in the function expression // (3) Function expressions can also pass parameters
9, Scope
1. Scope
"Scope" the name used in a piece of program code is not always valid and reliable, and the scope of the availability code that limits the name is the scope of the name.
-
The use of scope improves the locality of program logic, enhances the reliability of program, and reduces name conflict.
-
Before ES6, there were two scopes: global scope and local scope (function scope)
Global scope is used for all code execution environments (within the entire script tag) or an independent js file.
"Local scope" acts on the code environment inside the function, which is the local scope. Because it is related to functions, it is also called function scope.
"JS has no block level scope"
-
Block scope is included by {}
-
In other programming languages, in the if statement, the variables created by the loop statement can only be used in this if statement and this loop statement, as shown below 👇👇
if(true){ int num = 123; System.out.print(num); //123 } System.out.print(num);//report errors
-
The above java code will report an error because {} in the code is a scope, and the declared variable num cannot be used outside {}, while JavaScript code will not report an error
-
No block level scope in Js (before ES6)
if(true){ var num = 123; console.log(num); // 123 } console.log(num);// 123
2. Scope of variable
In JavaScript, variables can be divided into two types according to different scopes: 👇
-
global variable
-
local variable
Global variables are variables declared under the global scope (variables defined outside the function)
-
Global variables can be used anywhere in the code
-
The variables declared by var under the global scope are global variables
-
In special cases, variables that are not declared with var in a function are also global variables (not recommended).
Local variable is a variable declared under the local scope (a variable defined inside a function)
-
Local variables can only be used inside functions
-
The variables declared by var inside the function are local variables
-
The formal parameters of a function are actually local variables
"Difference between global variables and local variables"
-
Global variable: it can be used anywhere. It will be destroyed only when the browser is closed, so it takes up more memory
-
Local variable: intended for internal use in a function. It will be initialized only when the code block in which it is located is executed; After the contemporary code block runs, it will be destroyed, so it saves more memory space.
3. Scope chain
Scope chain: as long as the code is in one scope, it is written in the local scope inside the function, and it is still in the global scope without unloading and within the number of lines; If there are functions in the function, another scope can be born in this scope; According to the mechanism that internal functions can access external function variables, using chain search to determine which data can be accessed by internal functions is called scope chain.
Scope chain: the internal function accesses the variables of the external function and uses the chain search method to determine the value. This structure is called the scope chain proximity principle
function f1() { var num = 123; function f2() { console.log( num ); } f2(); } var num = 456; f1();
The scope chain uses the proximity principle to find the final value of the variable
var a = 1; function fn1() { var a = 2; var b = '22'; fn2(); function fn2() { var a = 3; fn3(); function fn3() { var a = 4; console.log(a); //Value of a = 4 console.log(b); //Value of b '22' } } } fn1();
10, Pre analysis
"1. Relevant concepts of pre analysis"
Javascript code is executed by a JavaScript parser in the browser. The JavaScript parser runs JavaScript code in two steps: pre parsing and code execution.
-
Pre parsing: under the current scope, before JS code execution, the browser will declare or define variables with var and function declarations in memory by default.
-
Code execution executes JS statements from top to bottom
Pre parsing completes the declaration of variables and functions before code execution. Pre parsing is also called variable and function promotion.
"2. Variable pre parsing (variable promotion)"
The declaration of the variable will be promoted to the top of the current scope, and the assignment of the variable will not be promoted.
console.log(num); //What's the result? var num = 10; // ? amount to var num; console.log(num);//The result is undefined num = 10;
result: undefined be careful: Variable promotion only promotes declarations, not assignments.
"3. Function pre parsing (function promotion)"
The declaration of the function will be promoted to the top of the current scope, but the function will not be called.
fn(); function fn() { console.log('Print'); }
result: Console print string --- "Print" be careful: The function declaration represents the whole function, so after the function is promoted, the function name represents the whole function, but the function is not called!
"4. Function expression declaration problem"
When a function is created by a function expression, the variable promotion will be executed. At this time, the variable name of the receiving function cannot be called correctly fn(); var fn = function(){ console.log("I don't think so"); }
result:Error reporting prompt "fn is not a function" explain: Before the code is executed, the variable declaration will be promoted, fn Value after promotion yes undefined;and fn Call is in fn Before being assigned to the function body, here fn The value of is undefined,So it can't be called.
"5. Case"
Pre analysis case 1 var num = 10; fun(); function fun(){ console.log(num); var num = 20; } This is equivalent to performing the following operations Result printing undefined var num; function fun(){ var num; console.log(num); num = 20; } num = 10; fun();
Pre analysis case 2 var a = 18; f1(); function f1(){ var b = 9; console.log(a); console.log(b); var a = '123'; } This is equivalent to performing the following operations The result is undefined 9 var a; function f1(){ var b; var a; b = 9; console.log(a); console.log(b); a = '123'; } a = 18; f1();
Pre analysis case 3 f1(); console.log(c); console.log(b); console.log(a); function f1() { var a = b = c = 9; console.log(a); console.log(b); console.log(c); } This is equivalent to performing the following operations The result is 9 9 9 9 9 "report errors--a is not defined" function f1() { var a; a = b = c = 9; //Equivalent to var a = 9; b=9; c=9; b and C are assigned directly, without var declaration, when viewed as global variables. //Difference: collective declaration var a = 9,b = 9, c = 9; console.log(a); console.log(b); console.log(c); } f1(); console.log(c); console.log(b); console.log(a);
11, Complex data type object
1. Concept of object
"Object" in JavaScript, an object is an unordered collection of related attributes and methods. All things are objects, such as strings, values, arrays, functions, etc.
-
Objects are composed of properties and methods
-
-
Attribute: the characteristic of a thing, which is represented by an attribute in an object (a common noun)
-
Method: the behavior of things is often expressed in the object (common verb)
-
"Why do you need objects?"
-
When saving a value, you can use variables. When saving multiple values (a group of values), you can use arrays. What if you save the complete information of one?
-
In order to better store a set of data, object application is born; The attribute name is set for each item of data in the object, which can access the data more semantically, with clear data structure and obvious meaning, which is convenient for developers to use.
var obj = { "name":"fan", "sex":"male", "age":18, "height":155 }
2. Three ways to create objects
"1. Create object with literal"
1. Create objects using object literals
-
The curly braces {} contain the attributes and methods to express the specific object (object); the curly braces {} are expressed in the form of key value pairs - key: equivalent to attribute name value: equivalent to attribute value, and can be any type of value (number type, string type, boolean type, function type, etc.)
//star # is the object created var star = { name : 'pink', age : 18, sex : 'male', sayHi : function() { alert('Hello, everyone'); } };
2. Use of objects
-
Attribute of object: the key in the "key value pair" in which specific data is stored in the object is called the attribute of the object, that is, the item in which specific data is stored in the object.
-
Object method: the "key" in the "key value pair" of the stored function in the object is called the object method, that is, the item of the stored function in the object.
-
Accessing the properties of an object: calling the properties in the object Attribute name; Another way to call attributes in an object: Object ['attribute name']. Note that the attributes in square brackets must be quoted.
-
Method of calling object: object Method name ();
console.log(star.name) //Call name property console.log(star['name']) //Call name property star.sayHi();
3. Summary of variables, attributes, functions and methods
① Variable: declare and assign values separately and exist separately ② attribute: the variables in the object are called attributes and do not need to be declared. They are used to describe the characteristics of the object. ③ Method: a method is a part of an object, a function is not a part of an object, and a function is a container that encapsulates operations separately. The function in the object is called a method. The method does not need to be declared. It can be called by using "object. Method name ()". The method is used to describe the behavior and function of the object. ④ Function: it exists separately and can be called by "function name ()".
// Differences among variables, attributes, functions and methods // 1. The similarities between variables and attributes are used to store data var num = 10; var obj = { age: 18, fn: function() { } } function fn() { } console.log(obj.age); // console.log(age); // Variables are declared and assigned separately. When used, the list of variables is written directly // Attributes in objects that do not need to be declared must be objects attribute // 2. The same point between functions and methods is to realize a function and do something // The function is declared separately and the function name () called exists separately // Method is called inside an object Method ()
"2. Create an object using new Object"
1. Create an empty object
Through the built-in constructor Object The object is created and the andy The variable has saved the created empty object var andy = new Object();
2. Add properties and methods to the empty object
Add attributes and methods to objects by manipulating them obj.uname = 'Zhang Sanfeng'; obj.age = 18; obj.sex = 'male'; obj.sayHi = function() { console.log('hi~'); } // (1) We use the equal sign = assignment method to add the properties and methods of the object // (2) Each property and method ends with a semicolon console.log(obj.uname); console.log(obj['sex']); obj.sayHi();
"3. Create object using constructor"
1. Why do I need a constructor
<script> // Why do we need to use constructors // This is because we can only create one object at a time in the previous two methods of creating objects var ldh = { uname: 'Lau Andy', age: 55, sing: function() { console.log('Ice rain'); } } var zxy = { uname: 'Xue You Zhang', age: 58, sing: function() { console.log('Li Xianglan'); } } // Because we create one object at a time, many of its properties and methods are the same, and we can only copy them // So we can use the method of function to repeat the same code, and we call this function constructor // And because this function is different, it encapsulates not ordinary code, but objects // Constructor is to abstract some of the same properties and methods in our object and encapsulate them in the function </script>
2. Create objects using constructors
Constructor is a special function, which is mainly used to initialize an object, that is, to assign initial values to object member variables. It is always used together with the new operator. We can extract some public properties and methods from the object and encapsulate them into this function.
-
Encapsulation format of constructor:
function Constructor name(Parameter 1, parameter 2, parameter 3...) { this.Property name 1 = Parameter 1; this.Property name 2 = Parameter 2; this.Property name 3 = Parameter 3; this.Method name = Function body; }
- Call format of constructor
var obj = new Constructor name(Argument 1, argument 2, argument 3); // In the above code, obj receives the object created by the constructor. matters needing attention: 1.Constructor convention initial capitalization 2.The properties and methods in the function need to be added in front this,Represents the properties and methods of the current object 3.Not required in constructor retrun Return results 4.But when we create objects, we must use new To call the constructor
function Star(uname, age, sex) { this.name = uname; this.age = age; this.sex = sex; this.sing = function(sang) { console.log(sang); } } var ldh = new Star('Lau Andy', 18, 'male'); // The calling function returns an object // console.log(typeof ldh); console.log(ldh.name); console.log(ldh['sex']); ldh.sing('Ice rain'); var zxy = new Star('Xue You Zhang', 19, 'male'); console.log(zxy.name); console.log(zxy.age); zxy.sing('Li Xianglan') // 1. The constructor name should be capitalized // 2. Our constructor can return results without return // 3. We must use new when calling the constructor // 4. As long as we call the function of new Star(), we will create an object ldh {} // 5. We must add this before our properties and methods
3. Constructors and objects
1. The constructor, such as Stars(), extracts the public part of the object and encapsulates it into the function. It {generally refers to a large class
2. Create objects, such as new Stars(); This refers specifically to the process of creating an object using the new keyword, which is also called object instantiation
<script> // Constructors and objects // 1. Constructor refers to a large class, which is similar to the class in java language function Star(uname, age, sex) { this.name = uname; this.age = age; this.sex = sex; this.sing = function(sang) { console.log(sang); } } // 2. Object refers to a specific thing, Andy Lau = = {name: "Andy Lau", age: 18, sex: "male", sing: ƒ} var ldh = new Star('Lau Andy', 18, 'male'); // The calling function returns an object console.log(ldh); // 3. The process of creating objects using constructors is also called object instantiation </script>
3. Function of new keyword (interview question)
-
-
1. Create an empty object before the constructor code starts executing;
-
2. Modify the point of this and point this to the created empty object;
-
3. Execute the code in the constructor and add properties and methods to the new object
-
4. After the function is completed, return the created new object (so return is not required in the constructor)
-
// The factory function creates an object, which returns the created object to the function call function createPerson(name, age, job) { var person = new Object(); person.name = name; person.age = age; person.job = job; person.sayHi = function(){ console.log('Hello,everyBody'); } return person; } var p1 = createPerson('Zhang San', 22, 'actor');
4. Traversal object
for...in Statement is used to perform a circular operation on the attributes of an array or object. The syntax is as follows: for (variable in Object name) { // Execute code here } The variable in the syntax is user-defined. It needs to comply with the naming convention. Usually, we will write this variable as k perhaps key. for (var k in obj) { console.log(k); // k here is the attribute name console.log(obj[k]); // obj[k] here is the attribute value }
<script> // Traversal object var obj = { name: 'pink teacher', age: 18, sex: 'male', fn: function() {} } for (var k in obj) { console.log(k); // The output of k variable is the attribute name console.log(obj[k]); // obj[k] gets the attribute value } // We use the variables in for in. We like to write k or key </script>
12, Built in object
There are three kinds of objects in the built-in object JavaScript: custom object, built-in object and browser object. The first two objects are the basic content of JS and belong to ECMAScript; The third browser object is unique to JS. JS API explains that built-in objects refer to some objects of JS language. These objects are used by developers and provide some common or most basic rather than necessary functions (properties and methods). The biggest advantage of built-in objects is to help us develop quickly.
"Check the document" to learn how to use a built-in object. As long as we learn how to use its common members, we can learn by checking the document. MDN: https://developer.mozilla.org/zh-CN/
1. Math object
"Math object"
It's not a constructor, so we don't need new to call, but just use the properties and methods inside
It has the properties and methods of mathematical constants and functions, which is related to mathematics.
Property, method name | function |
---|---|
Math.PI | PI |
Math.floor() | Round down |
Math.ceil() | Round up |
Math.round() | The rounded version is rounded to the nearest. Note - 3.5. The result is - 3 |
Math.abs() | absolute value |
Math.max()/Math.min() | Find the maximum and minimum values |
Math.random() | Gets a random value in the range [0,1] |
<script> // Math object is not a constructor, so we don't need new to call it, but just use the properties and methods inside console.log(Math.PI); // An attribute pi console.log(Math.max(1, 99, 3)); // 99 console.log(Math.max(-1, -10)); // -1 console.log(Math.max(1, 99, 'pink teacher')); // NaN console.log(Math.max()); // -Infinity </script>
Gets a random integer in the specified range
function getRandom(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; }
<script> // 1.Math object random number method random() returns a random decimal 0 = < x < 1 // 2. There are no parameters in this method // 3. Code verification console.log(Math.random()); // 4. We want to get a random integer between two numbers and include these two integers // Math.floor(Math.random() * (max - min + 1)) + min; function getRandom(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } console.log(getRandom(1, 10)); // 5. Random roll call var arr = ['Zhang San', 'Zhang Sanfeng', 'Zhang San madman', 'Li Si', 'Li sisi', 'pink teacher']; // console.log(arr[0]); console.log(arr[getRandom(0, arr.length - 1)]); </script>
<script> // Figure guessing game // 1. Generate an integer of 1 ~ 10 randomly. We need math Random() method. // 2. You need to guess until you are right, so you need to cycle all the time. // 3. The while loop is simpler // 4. Core algorithm: use if else if multi branch statements to judge greater than, less than and equal to. function getRandom(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } var random = getRandom(1, 10); while (true) { // Dead cycle var num = prompt('Guess what? Input 1~10 A number between'); if (num > random) { alert('Guess it's too big'); } else if (num < random) { alert('Guess it's small'); } else { alert('You're handsome. You're right'); break; // Exit the whole cycle end program } } // Users are required to guess a number between 1 and 50, but they have only 10 chances to guess </script>
2. Date object
Date object is different from Math object. Date is a constructor, so you need to instantiate it before you can use its specific methods and properties. The date instance is used to process date and time
1. Instantiate Date object with date
-
-
Get current time must be instantiated
-
Gets the date object for the specified time
-
var now = new Date(); //Get current time must be instantiated console.log(now); var date = new Date(); // 1. Use Date. If there is no parameter, return the current time of the current system var future = new Date('2020/10/1') // 2. The common writing method of the parameter is numeric 2019, 10, 01 or string '2019-10-1 8:8:8' // Note: if no parameter is passed in when creating an instance, the date object obtained is the date object corresponding to the current time
2. Date format: mm / DD / yy
Methods and properties using Date instances
Month obtained by getMonth() method + 1 = current month
//Parameters are usually written in numeric or string form '2019-10-1 8:8:8' var date1 = new Date(2019,10,1);
//Date formatting // Format date: mm / DD / yy var date = new Date(); console.log(date.getFullYear()); //Returns the year 2020 of the current date console.log(date.getMonth() + 1); //The month returned in the month is 1 month smaller. Remember to add 1 month to the month console.log(date.getDate()); //What number is returned console.log(date.getDay); //Monday returns 1, Saturday returns 6, and Sunday returns 0 //We write a Sunday, September 6, 2020 var year = date.getFullYear(); var month = date.getMonth() + 1; var dates = date.getDate(); var day = date.getDay(); if (day == 0) { day = "Sunday"; } console.log("Today is" + year + "year" + month + "month" + dates + "day" + day);
3. Format date hour, minute and second
<script> // Format date hour minute second var date = new Date(); console.log(date.getHours()); // Time console.log(date.getMinutes()); // branch console.log(date.getSeconds()); // second // It is required to encapsulate a function to return the current time, minute and second format 08:08:08 function getTimer() { var time = new Date(); var h = time.getHours(); h = h < 10 ? '0' + h : h; var m = time.getMinutes(); m = m < 10 ? '0' + m : m; var s = time.getSeconds(); s = s < 10 ? '0' + s : s; return h + ':' + m + ':' + s; } console.log(getTimer()); </script>
4. Get the total number of milliseconds (timestamp) of Date
<script> // The total number of milliseconds (timestamp) obtained from Date is not the number of milliseconds of the current time, but the number of milliseconds since January 1, 1970 // 1. Use valueof() gettime() var date = new Date(); console.log(date.valueOf()); // It's our present time distance 1970.1 1 total milliseconds console.log(date.getTime()); // 2. Simple writing method (the most commonly used writing method) var date1 = +new Date(); // +new Date() returns the total number of milliseconds console.log(date1); // 3. The total number of milliseconds added in H5 console.log(Date.now()); </script>
5. Countdown (timestamp)! Key
- Based on milliseconds since January 1, 1970 (world standard)
// Instantiate Date object var now = new Date(); // 1. Used to obtain the original value of the object console.log(now.valueOf()) console.log(now.getTime()) // 2. Simple writing can do this (the most commonly used) var now = + new Date(); // 3. The method provided in HTML5 has compatibility problems var now = Date.now();
// Countdown effect // 1. Core algorithm: the input time minus the current time is the remaining time, that is, the countdown, but you can't subtract the hours, minutes and seconds. For example, if you subtract 25 minutes from 05 minutes, the result will be negative. // 2. Do it with time stamp. The total number of milliseconds of the user input time minus the total number of milliseconds of the current time is the number of milliseconds of the remaining time. // 3. Convert the total milliseconds of the remaining time into days, hours, minutes and seconds (the timestamp is converted to minutes and seconds) // The conversion formula is as follows: // D = parseInt (total seconds / 60 / 60 / 24)// Calculation days // H = parseInt (total seconds / 60 / 60% 24) / / calculate hours // M = parseInt (total seconds / 60% 60)// Calculate score // S = parseInt (total seconds% 60)// Calculate current seconds // Implementation of countdown case encapsulation function function countDown(time) { var nowTime = +new Date(); // Returns the total number of milliseconds of the current time var inputTime = +new Date(time); // Returns the total number of milliseconds of user input time var times = (inputTime - nowTime) / 1000; // times is the total number of seconds remaining var d = parseInt(times / 60 / 60 / 24); // day d = d < 10 ? '0' + d : d; var h = parseInt(times / 60 / 60 % 24); //Time h = h < 10 ? '0' + h : h; var m = parseInt(times / 60 % 60); // branch m = m < 10 ? '0' + m : m; var s = parseInt(times % 60); // Current seconds s = s < 10 ? '0' + s : s; return d + 'day' + h + 'Time' + m + 'branch' + s + 'second'; } console.log(countDown('2019-5-1 18:00:00')); var date = new Date(); console.log(date);
3. Array object
"1. Two ways to create arrays"
-
1. Literal var arr = [1,"test",true];
-
2. Instantiate the array object new Array()var arr = new Array();
-
-
Note: in the above code, arr creates an empty Array. If you need to use the constructor Array to create a non empty Array, you can pass in parameters when creating the Array
-
If only one parameter (number) is passed in, the parameter specifies the length of the array.
-
If more than one parameter is passed in, the parameter is called an element of the array.
// Two ways to create arrays // 1. Use array literal var arr = [1, 2, 3]; console.log(arr[0]); // 2. Use new Array() // var arr1 = new Array(); // An empty array was created // var arr1 = new Array(2); // This 2 indicates that the length of the array is 2 and there are 2 empty array elements in it var arr1 = new Array(2, 3); // Equivalent to [2,3], it means that there are two array elements, 2 and 3 console.log(arr1);
"2. Check whether it is an array"
-
1. instanceof operator
-
-
instanceof can determine whether an object is an instance of a constructor
var arr = [1, 23]; //array var obj = {}; //object console.log(arr instanceof Array); // true console.log(obj instanceof Array); // false
-
-
-
2. Array.isArray()
-
-
Array.isArray() is used to determine whether an object is an Array.isArray() is a method provided in HTML5
-
var arr = [1, 23]; var obj = {}; console.log(Array.isArray(arr)); // true console.log(Array.isArray(obj)); // false
// Flip array function reverse(arr) { // if (arr instanceof Array) { if (Array.isArray(arr)) { var newArr = []; for (var i = arr.length - 1; i >= 0; i--) { newArr[newArr.length] = arr[i]; } return newArr; } else { return 'error This parameter must be in array format [1,2,3]' } } console.log(reverse([1, 2, 3])); console.log(reverse(1, 2, 3));
-
3. Pay attention to the usage of typeof
-
-
typeof is used to determine the type of variable
-
var arr = [1, 23]; console.log(typeof arr) // The object object arr is an instance of the constructor and is therefore an object data type
"3. Methods for adding and deleting array elements"
There are methods to add and delete elements in the array. Some methods are shown in the table below 👇
// 1. push() adds one or more array elements to the end of our array var arr = [1, 2, 3]; // arr.push(4, 'pink'); console.log(arr.push(4, 'pink')); console.log(arr); // (1) push is a new element that can be appended to the array // (2) Just write the array element directly with the push () parameter // (3) After the push is completed, the returned result is the length of the new array // (4) The original array will also change // 2. unshift add one or more array elements at the beginning of our array console.log(arr.unshift('red', 'purple')); console.log(arr); // (1) unshift is a new element that can be appended to the front of the array // (2) The unshift () parameter can be written directly to the array element // (3) After unshift, the returned result is the length of the new array // (4) The original array will also change // 3. pop() which can delete the last element of the array console.log(arr.pop()); console.log(arr); // (1) pop is the last element of the array that can be deleted. Remember that only one element can be deleted at a time // (2) pop() has no parameters // (3) After pop, the returned result is the deleted element // (4) The original array will also change // 4. shift() which can delete the first element of the array console.log(arr.shift()); console.log(arr); // (1) shift is the first element of the array that can be deleted. Remember that only one element can be deleted at a time // (2) shift() has no parameters // (3) After the shift is completed, the returned result is the deleted element // (4) The original array will also change
<script> // There is an array containing wages [1500, 1200, 2000, 2100, 1800]. It is required to delete those whose wages exceed 2000 in the array and put the rest in the new array var arr = [1500, 1200, 2000, 2100, 1800]; var newArr = []; for (var i = 0; i < arr.length; i++) { if (arr[i] < 2000) { // newArr[newArr.length] = arr[i]; newArr.push(arr[i]); } } console.log(newArr); </script>
"4. Array sorting"
-
There are methods to sort the array itself in the array. Some methods are shown in the table below
Method name | explain | Modify original array |
---|---|---|
reverse() | Invert the order of elements in the array without parameters | This method will change the original array and return a new array |
sort() | Sort the elements of the array | This method will change the original array and return a new array |
-
Note: the sort method needs to pass in parameters (functions) to set ascending and descending sorting
-
-
If "function (a, b) {return A-B;}" is passed in, In ascending order
-
If "function (a, b) {return B-A;}" is passed in, In descending order
-
// 1. Flip array var arr = ['pink', 'red', 'blue']; arr.reverse(); console.log(arr);
// 2. Array sorting (bubble sorting) var arr1 = [13, 4, 77, 1, 7]; arr1.sort(function(a, b) { // return a - b; Ascending order return b - a; // Descending order }); console.log(arr1);
"5. Array index method"
There are methods to obtain the index value of the specified element of the array. Some methods are shown in the table below
var arr = [1, 2, 3, 4, 5, 4, 1, 2]; // Find index of element 2 console.log(arr.indexOf(2)); // 1 // Find the last index of element 1 in the array console.log(arr.lastIndexOf(1)); // 6
Array de duplication: key cases
// Array de duplication ['c ',' a ',' Z ',' a ',' x ',' a ',' x ',' C ',' B '] requires the removal of duplicate elements in the array. // 1. Objective: select the non duplicate elements in the old array and put them into the new array. Only one duplicate element is retained and put them into the new array for duplication. // 2. Core algorithm: we traverse the old array, and then take the old array element to query the new array. If the element has not appeared in the new array, we will add it, otherwise we will not add it. // 3. How do we know that the element does not exist? Use the new array Indexof (array element) if - 1 is returned, it means that there are no changed elements in the new array // Encapsulating a de duplication function unique function unique(arr) { var newArr = []; for (var i = 0; i < arr.length; i++) { if (newArr.indexOf(arr[i]) === -1) { newArr.push(arr[i]); } } return newArr; } // var demo = unique(['c', 'a', 'z', 'a', 'x', 'a', 'x', 'c', 'b']) var demo = unique(['blue', 'green', 'blue']) console.log(demo);
"6. Convert array to string"
There are methods to convert an array into a string in the array. Some methods are shown in the table below
Note: if the join method does not pass in parameters, the elements will be spliced according to ","
var arr = [1, 2, 3, 4]; var arr2 = arr; var str = arr.toString(); // Convert array to string console.log(str); // 1,2,3,4
// Join (delimiter) converts an array to a string according to the characters you type var arr1 = ['green', 'blue', 'pink']; console.log(arr1.join()); // green,blue,pink console.log(arr1.join('-')); // green-blue-pink console.log(arr1.join('&')); // green&blue&pink
"7. Other methods"
var arr = [1, 2, 3, 4]; var arr2 = [5, 6, 7, 8]; var arr3 = arr.concat(arr2); console.log(arr3); // [1,2,3,4,5,6,7,8] // slice(begin,end) is a left closed right open interval [1,3] // Intercept from index 1 to index 3 var arr4 = arr.slice(1, 3); console.log(arr4); // [2,3] var arr5 = arr2.splice(0, 3); console.log(arr5); // [5,6,7] console.log(arr2); // [8] Splice() affects the original array
4. String object
"1. Basic package type"
To facilitate the manipulation of basic data types, JavaScript also provides three special reference types: String, Number, and Boolean. The basic wrapper type is to wrap a simple data type into a complex data type, so that the basic data type has properties and methods.
// What's wrong with the following code? var str = 'andy'; console.log(str.length); // 4
In principle, basic data types have no attributes and methods, while objects have attributes and methods, but the above code can be executed because js will package basic data types as complex data types. The execution process is as follows:
// 1. Generate temporary variables and wrap simple types into complex data types var temp = new String('andy'); // 2. Assign a value to the character variable we declare str = temp; // 3. Destroy temporary variables temp = null;
"2. Immutability of string"
-
It means that the value inside is immutable. Although it seems that the content can be changed, in fact, the address has changed and a new memory space has been opened up in the memory.
-
When re assigning a value to a string variable, the previously saved string of the variable will not be modified. Re assigning a value to the string in memory will re open up space in memory. This feature is the immutability of the string.
-
Due to the immutability of strings, there will be efficiency problems when "splicing a large number of strings"
"3. Return position according to characters"
String through the basic wrapper type, you can call some methods to operate the string. The following is the method to return the position of the specified character:
var str = "anndy"; console.log(str.indexOf("d")); // 3 //Specifies that the character "d" is found starting at an index number of 4 console.log(str.indexOf("d", 4)); // -1 console.log(str.lastIndexOf("n")); // 2
Case: find the location and number of occurrences of all o in the string "abcoefoxyozopp"
-
First find the location where the first o appears
-
Then, as long as the result returned by indexOf is not - 1, continue to look back
-
Because indexOf can only find the first one, the subsequent search uses the second parameter to add 1 to the current index to continue the search
var str = "oabcoefoxyozzopp"; var index = str.indexOf("o"); var num = 0; while (index !== -1) { console.log(index); num++; index = str.indexOf("o", index + 1); } console.log('o The number of occurrences is: ' + num);
"4. Return character by position" key
String through the basic wrapper type, you can call some methods to operate the string. The following is the character at the specified position returned according to the position:
// Returns characters based on position // 1. charAt(index) returns characters according to position var str = 'andy'; console.log(str.charAt(3)); // y // Traverse all characters for (var i = 0; i < str.length; i++) { console.log(str.charAt(i)); } // a n d y // 2. charCodeAt(index) //Returns the character ASCII value of the corresponding index number. Purpose: to determine which key the user pressed console.log(str.charCodeAt(0)); // 97 // 3. str[index] H5 NEW console.log(str[0]); // a
Case: judge the character that appears the most times in a string 'abcoefoxyozzopp', and count its times
-
-
Core algorithm: use charAt() to traverse this string
-
Store each character to the object. If the object does not have this attribute, it will be 1. If it exists, it will be + 1
-
Traverse the object to get the maximum value and the character. Note: in the process of traversal, each character in the string is stored in the object as the attribute of the object, and the corresponding attribute value is the number of occurrences of the character
-
var str = "abcoefoxyozzopp"; var o = {}; for (var i = 0; i < str.length; i++) { var chars = str.charAt(i); // chars is each character of the string if (o[chars]) { // o[chars] gets the attribute value o[chars]++; } else { o[chars] = 1; } } //1. Store each character to the object console.log(o); // 2. Traversing objects var max = 0; var ch = ""; for (var k in o) { // k is the attribute name // o[k] gets the attribute value if (o[k] > max) { max = o[k]; ch = k; } } console.log(max); console.log("The maximum number of characters is" + ch);
"5. String operation method"
String through the basic wrapper type, you can call some methods to operate the string. The following are some operation methods:
// 1. concat('string 1 ',' string 2 '...) var str = 'andy'; console.log(str.concat('red')); // andyred
// 2. substr('intercept start position ',' intercept several characters'); var str1 = 'The spring breeze of reform is blowing all over the ground'; // The first 2 is the 2 of the index number, starting from the second 2, and the second 2 is the number of characters console.log(str1.substr(2, 2)); // spring breeze
-
replace() method
-
-
The replace() method is used to replace some characters with others in the string. Its format is as follows:
-
character string.replace(The string to be replaced, the string to be replaced with);
// 1. The replacement character replace('replaced character ',' replaced character ') will only replace the first character var str = "andyandy"; console.log(str.replace("a", "b")); // bndyandy // There is a string 'abcoefoxyozzopp' that requires all o's in it to be replaced with* var str1 = "abcoefoxyozzopp"; while (str1.indexOf("o") !== -1) { str1 = str1.replace("o", "*"); } console.log(str1); // abc*ef*xy*zz*pp
-
split() method
-
-
The split() method is used to split strings, which can be split into arrays. After segmentation, a new array is returned.
-
Its format is as follows:
-
character string.split("Split character")
// 2. Convert characters to array split('separator ') // We learned earlier that join converts an array into a string var str2 = "red, pink, blue"; console.log(str2.split(",")); //[red,pink,blue] var str3 = "red&pink&blue"; console.log(str3.split("&")); // [red,pink,blue]
13, Simple and complex data types
"Simple type (basic data type, value type)": during storage, the value itself is stored in the variable, including string, number, boolean, undefined and null
// The simple data type null returns an empty object object var timer = null; console.log(typeof timer); // If we plan to store a variable as an object in the future and don't think about what to put for the time being, it will be null at this time // 1. Simple data types are stored in the stack. A space is directly opened in the stack to store values // 2. Complex data types first store the address hexadecimal representation in the stack, and then this address points to the data in the heap
"Complex data type (reference type)": during storage, only the address (Reference) is stored in the variable. Objects (system objects, user-defined objects) created through the new keyword, such as Object, Array, Date, etc;
"1. Stack"
-
Stack space allocation difference:
-
-
1. Stack (operating system): the operating system automatically allocates and releases the parameter values and local variable values of the stored function. Its operation mode is similar to the stack in the data structure;
-
Simple data types are stored on the stack
-
2. Heap (operating system): it stores complex types (objects), which are generally allocated and released by the programmer. If the programmer does not release them, they are collected by the garbage collection mechanism.
-
Storage of simple data types
-
The data of value type variables is stored directly in variables (stack space)
Storage of complex data types
-
Reference type variables (stack space) store addresses, and real object instances are stored in heap space
2. Simple type parameters
The formal parameter of a function can also be regarded as a variable. When we pass a value type variable as a parameter to the formal parameter of a function, we actually copy the value of the variable in the stack space to the formal parameter. Then any modification to the formal parameter inside the method will not affect the external variable.
function fn(a) { a++; console.log(a); } var x = 10; fn(x); console.log(x);
"3. Complex data type parameter transfer"
The formal parameter of a function can also be regarded as a variable. When we pass a reference type variable to the formal parameter, we actually copy the heap address saved by the variable in the stack space to the formal parameter. The formal parameter and the actual parameter actually save the same heap address, so we operate on the same object.
function Person(name) { this.name = name; } function f1(x) { // x = p console.log(x.name); // 2. What is this output? x.name = "Xue You Zhang"; console.log(x.name); // 3. What is this output? } var p = new Person("Lau Andy"); console.log(p.name); // 1. What is this output? f1(p); console.log(p.name); // 4. What is this output?