Recently, I found some tutorials to relearn (review) JavaScript. By the way, I sorted the learning contents into notes to consolidate the knowledge I learned. At the same time, I also referred to the contents of some blogs and books to check for omissions and fill gaps and recharge myself
In order to improve the development efficiency, the first choice for front-end development is: VSCode(Visual Studio Code).New JavaScript
Brendan EICH, the "founder", was originally named LiveScript. Later, Sun acquired and renamed JavaScript.
"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.
"JavaScript composition" ECMAScript(JavaScript syntax), DOM (document object model), BOM (browser object model)
JavaScript Role of
- 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)
"JavaScript 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 = "javascript.js"></script>
"Notes"
- Single-Line Comments
// I am a single line comment (Shortcut 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 alt + shift + a) is changed to (ctrl + shift + /) */
variable
Concept of variable
Variables are containers for storing data. You can obtain data or even modify data through variable names.
Use of variables
"1. Declare variables"
// 1. Declare variables var num; // Declare a variable named num
var is a JS keyword used to declare variables. num is a custom variable name. You can access the space allocated in memory and call variables 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, that is, the variable value shall be subject to the last assignment. var num = 10; num = 11; // 2. Declare multiple variables at the same time (only one var needs to be written, and multiple variable names are separated by English commas) var num = 10, age = 999, name = 'Joshua';
Declare variable special cases
situation | explain | result |
---|
"5. Variable naming specification"
data type
There are two types: simple data types (Number,String,Boolean,Undefined,Null) and complex data types (objects).
Simple data type | explain | Default value |
---|
Number numeric
"Numeric base"
// 1. Add 0 before octal and 0x before hexadecimal in JS 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 , Infinity , Infinity , Infinity , Infinity , Infinity , Infinity , Infinity
- isNaN(): used to determine whether a variable is of non numeric type. The non numeric type is true and the numeric type is false.
String string type
// 1. The string type can be any text in quotation marks. The syntax is single quotation marks and double quotation marks var msg = 'My name is'; var name = "fan";
"1. String escape character"
Escape character | explain |
---|
"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. The syntax is single quotation marks and double quotation marks var msg = 'Like collection after learning'; 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 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");
Boolean
Boolean types have two values: true and false, where true represents true (right) and false represents false (wrong). 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
Undefined and Null
If a variable is declared without assignment, it will have a default value of undefined
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
Get variable type and conversion
- Detect the data type of the variable
var num = 10; console.log(typeof num)//The result is number
- Literal quantity: it is the representation of a fixed value in the source code, that is, how to express this value. The type of data can be determined by the format characteristics of the data
- Number literal: 8,9,10
- String literal: 'javascript', 'front end development'
- Boolean literal: true,false
Data type conversion
- Convert to string
mode | explain | case |
---|
- Convert to numeric
mode | explain | case |
---|
- 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 |
---|
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.
##
operator
Operator
It is a symbol used to realize the functions of assignment, comparison and arithmetic operation. It can be classified as:
- Arithmetic operator
- Increment and decrement operators
- Comparison operator
- Logical operator
- Assignment Operators
Arithmetic operator
operator | describe | case |
---|
- 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
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
Comparison operator
operator | describe | case | result |
---|
Logical operator the logical operator is an operator used for Boolean operations. Short circuit operations: when there are multiple expressions (values) and the expression value on the left can determine the result, the operation on the expression value on the right will not continue;
operator | describe | case | characteristic |
---|
Assignment operator
operator | describe | case |
---|
Operator priority
priority | operator | order |
---|
Process control
"Process control" during the execution of a program, the execution order of each code has a direct impact on the result of the program. Process control can control the execution order of code. The sequence structure, branch structure and loop structure represent the execution order of the three codes.
"Branch process control"
// 1. Code statement executed when the condition is true 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 }
"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;
"Switch branch process control" is used to execute different codes based on different conditions. When you want to set a series of options for a specific value for a variable, you can use switch.
switch( expression ){ case value1: // Code to execute when expression equals value1 break; case value2: // Code to execute when expression equals value2 break; default: // Code to execute when the expression is not equal to any value }
##
loop
operator | describe |
---|
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
"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);
"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, //Calculate the cumulative sum of 1-100 var i = 1; var sum = 0; while (i <= 100) { sum += i; i++; } console.log(sum);
"Do while loop"
do { // Loop body code - repeats the loop body code when the conditional 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);
"Continue, break" the "continue" keyword is used to immediately jump out of this cycle and continue the next cycle (the code after continue in the body of this cycle will be executed less once). The "break" keyword is used to immediately jump out of the whole cycle (the end of the cycle).
array
"1. The concept of array" is a set of data, in which each data is called an element, and 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]);//[] represents optional. If n is written, it represents 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 literal 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 element index (subscript): the sequence 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. Traversing the array" accesses the elements in the array 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 a new element 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. Case"
// 1. Filter the elements larger than 10 in the array, select them and put them into 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. Convert an array to a string and split it 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. Convert an array to a string and split it 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);
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
function
"1. Concept of function" encapsulates a code block that can be repeatedly called and executed. A large number of codes 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 the function, which must be lowercase // 1.2 name the function as a verb. 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 functions created by function expressions can be created by variable names (); 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...);
- "When the number of function parameters and arguments does not match"
Number of parameters | explain |
---|
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: the data represented by the whole function call; After the function is executed, you can return the specified data through the return statement.
// Declarative 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 break,continue,return Differences between
- 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 pits. 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
5. Use of arguments: when you are not sure how many parameters are passed, you can use arguments to obtain 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
function fn() { //Arguments stores all passed arguments console.log(arguments);// [1,2,3...] console.log(arguments[1]); // 2 console.log(arguments.length); // 3 //We can traverse the argument as an array } fn(1, 2, 3); // 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);
Code specification
1. Identifier naming convention
- The naming of variables and functions must be meaningful (easy to distinguish and facilitate later maintenance)
- 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 annotation 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++) {}
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 kinds of 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:
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
Scope of variable
In JavaScript, variables can be divided into two types according to different scopes:- global variable
- local variable
Global variable refers to the variable declared under the global scope (i.e. the variable 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.
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.
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();
Pre analysis
The "pre parsing related concepts" JavaScript code is executed by the 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.
"Variable pre resolution (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.
The declaration of "function pre parsing (function promotion)" 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!
"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. Pre analysis case 1 var num = 10; fun(); function fun(){ console.log(num); var num = 20; } It is equivalent to performing the following operations and printing the results 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'; } It is equivalent to performing the following operations, and 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); } It is equivalent to performing the following operations, and the result is 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);
object
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 }
Three ways to create objects
"1. Create object with literal" create object with literal:
- 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'); } };
- 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 ();
- Summary of variables, attributes, functions and methods: ① variables: declare and assign values separately and exist separately; ② attributes: variables in an object are called attributes and do not need to be declared 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 separately encapsulates operations. 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: if it exists alone, it can be called through "function name ()".
console.log(star.name) // Call name property console.log(star['name']) // Call name property star.sayHi();
"2. Create an object using new Object"
- 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();
- Add properties and methods to an empty object
Add attributes and methods to objects by manipulating them andy.name = 'pink'; andy.age = 18; // andy.age = 19 modify object properties andy.sex = 'Male;// andy.phoneNum = 110 add attribute andy.sayHi = function() { alert('hello everyone'); } obj.sayHi();Call the method of the object //The second is obj['sayHi '] (); // The first letter of Object() is capitalized; //new Object() requires the new keyword. The format used is: object Attribute = value
"3. Create object using constructor"
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 1.Others: constructors such as Stars(),The common part of the object is extracted and encapsulated into the function Generally refers to a large class(class) 2.Create objects, such as new Stars();Especially one that uses new Keyword the process of creating an object We also call it object instantiation
- 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');
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 }
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. The built-in objects explained by JS API refer to some objects of JS language, which are used by developers to help rapid development.
Math object
"Math object" is not a constructor. It has properties and methods of mathematical constants and functions, which is related to mathematics.
Property, method name | function |
---|
- Gets a random integer in the specified range function getRandom(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; }
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
- Instantiate a Date object with Date
- Get current time must be instantiated
- Gets the date object for the specified time
var now = new Date(); var future = new Date('2020/10/1') // Note: if no parameter is passed in when creating an instance, the date object obtained is the date object corresponding to the current time
- Continued
- 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); //Format date hour minute second var date = new Date(); console.log(date.getHours()); //Time console.log(date.getMinutes()); //branch console.log(date.getSeconds()); // second //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(); var h = h < 10 ? "0" + h : h; var m = time.getMinutes(); var m = m < 10 ? "0" + m : m; var s = time.getSeconds(); var s = s < 10 ? "0" + s : s; return h + ":" + h + ":" + s; } console.log(getTimer());
- Gets the total number of milliseconds (timestamp) of the Date. It is based on the number of milliseconds since January 1, 1970 (world standard world)
// 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 case: 1. The input time minus the current time is the remaining time, that is, the countdown. 2.The timestamp is used to subtract the total milliseconds of the current time from the total milliseconds of the user input time, The result is the number of milliseconds remaining 3.Convert the total milliseconds of the remaining time into days, hours, minutes and seconds (Timestamp conversion time, 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 minutes 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("2020-10-1 18:00:00")); var date = new Date(); console.log(date);
Array object
"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.
"Detect whether it is an array"
- 1. instanceof operator
- instanceof can determine whether an object is an instance of a constructor
var arr = [1, 23]; var obj = {}; 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
- 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
"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
var arr = [1, 2, 3]; console.log(arr.push(4, 5)); // 5 add elements to the end of the array arr.pop(); //Deletes the last value of the array and returns console.log(arr); // [1,2,3,4] // Adds an element to the beginning of an array and returns the length of the array console.log(arr.unshift(5, 6)); // 6 array becomes [5,6,1,2,3,4] console.log(arr.shift()); // 5 delete the element at the beginning of the array and return the value
Array sort
- 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 |
---|
- 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
// Pit array sort (bubble sort) return a - b will be in ascending order // The writing method is fixed as follows: var arr1 = [13,4,77,1,7]; arr1.sort(function(a,b){ return a-b; }); console.log(arr1);
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
"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 var str2 = arr2.join("|");//Converts an array to a string according to the characters you type console.log(str2);
"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
String object
Basic wrapper type to facilitate the operation 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;
"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"
"Return position according to character"
- 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); }
"Return character by position"
- 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; } } 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);
String operation method
- String through the basic wrapper type, you can call some methods to operate the string. The following are some operation methods:
// String operation method // 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);
- 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") // 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 // 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]
data type
"Simple type (basic data type, value type)": during storage, the value itself is stored in the variable, including string, number, boolean, undefined and null
"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;
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
The formal parameter of the "simple type parameter transfer" function can also be regarded as a variable. When we transfer a value type variable as a parameter to the formal parameter of the 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);
The operation results are as follows
The formal parameter of the complex data type parameter transfer 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.
PS
If you think this note is not comprehensive enough, or want to find some other IT tutorials and courses, you can open the following card and transfer to the official Netease cloud class:
[free collection] Netease product: UI Designer 3-day training camp (with Netease internal information + designer community attached)
Invalid
Netease cloud classroom focuses on Internet IT vocational skills teaching, including workplace office, programming, design, promotion, operation and other occupations. The main target groups are professionals and college students.