[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-n71fixw8-1619244581160) (C: \ users \ Juan ~ er \ appdata \ roaming \ typora user images \ image-20210410141227980. PNG)]
JavaScript Foundation
brief introduction
history
- JavaScript was born in 1995. NetSpace releases NetSpace navigator 2 browser and provides a free development tool LiveScript. The main purpose of the design is to handle some input verification operations previously undertaken by the server-side language. In the era when people generally use telephone dialing to surf the Internet, it is absolutely not easy to complete some basic verification tasks on the client. Because Java is popular, it is renamed JavaScript. This is JavaScript 1 Version 0.
- Because JavaScript is very popular, netspace navigator 3 browser released JavaScript 1 Version 1. Soon IE3 also added the function of script programming. In order to avoid disputes, it was named JScript.
- In 1997, ECMA launched JavaScript 1 1 as the basis, the script language standard ECMA-262 is formulated and named ECMAScript. Browser manufacturers use ECMAScript as the standard for their JavaScript implementation.
ECMAScript
- In 1997, ECMA issued the first edition of standard document No. 262 (ECMA-262), which stipulated the implementation standard of scripting language and named this standard ECMAScript, which is Es1 Version 0.
- ECMAScript is the standard of JavaScript language, and JavaScript is an implementation of ECMAScript. It is interchangeable in some contexts. ECMAScript specifies the components of the language: syntax, type, statement, keyword, reserved word, operator and object.
ECMAScript version
- June 1998, ecmascript2 Release 0
- December 1990, ecmascript3 Version 0 was released and has become a general standard for JavaScript, which has been widely supported
- October 2007, ecmascript4 Version 0 draft was released, and version 3.0 was greatly upgraded. Because the goal of version 4.0 is too radical, all parties have serious differences on whether to pass this standard. ECMA suspended ECMAScript 4.0 in July 2008 0, a small part of which involves the improvement of existing functions is published as ecmascript3 1. Soon, ecmascript3 1 renamed ECMAScript5
- December 2009, ecmascrip5 Version 0 officially released
- ECMAScript version 5.1 was released in June 2011
- In December 2013, ECMAScrip6 draft was released. In June 2015, ECMAScript6 was released as the official version and renamed ECMAScript2015. At present, the latest version is ECMAScript 2019, which was officially released in July 2019
Why learn js
- All major browsers support JavaScript.
- Currently, most web pages around the world use JavaScript.
- It can make web pages present various dynamic effects.
- As a Web developer, JavaScript is an essential tool if you want to provide beautiful Web pages and a satisfactory Internet experience for users
Usage scenario
- WEB front end
- Graphics processing
- PDF generation
- Graphical interface
- Various test tools
- Video and audio playback and processing
- signal communication
- Multi person collaboration
- back-end
- Node
- Development framework Express/ThinkJS/Clouda
- Blog system: Ghost/hexo
- Front end automation tool based on Node: Grunt/Gulp
- Hybrid App
- game
- Cocos2d, one of the most popular 2D game engines in the world, and Unity3D, one of the most popular 3D game engines, both support JS to develop games.
JavaScript concepts
JavaScript is a literal script language. It is a dynamic type, weak type, prototype based language with built-in support of types. Its interpreter is called JavaScript engine. It is a part of the browser. It is widely used in the client script language. It is used on HTML web pages to add dynamic functions to HTML web pages.
- Literal translation: it does not need to be compiled into machine code by the compiler, and then run directly in the CPU. Literal language needs to be translated dynamically during the run-time through the interpreter.
- Scripting language: JavaScript is interpreted line by line during the operation of the program, and only interpreted or compiled when called.
- Dynamic type: the type declaration is not required before the variable is used. Usually, the type of the variable is the type of the value assigned.
- Weak type: a language in which data types can be ignored. In contrast to strong type definition language, a variable can be assigned values of different data types
- Prototype based: only objects, no classes; Objects inherit objects, not classes. "Prototype object" is the core concept based on prototype language. A prototype object is a template for a new object that shares its properties with the new object. An object can not only enjoy the properties defined by its creation time and runtime, but also enjoy the properties of the prototype object
js composition
The complete JS consists of the following
- ECMAScript: the core part of the language
- Document object model (DOM), web document operation standard, HTML application programming interface (API), DOM maps the whole document into a tree node structure, which is convenient for JS scripts to access and operate quickly.
- The operation basis of browser object model (BOM) client and browser window. Using BOM, you can access and operate the browser window, such as moving window, access history, etc. there is no specification, but all browsers support it by default
JS preliminary use
js introduction
-
Script > tag
-
The main way to insert JavaScript into HTML pages is to use * < script > * elements
-
Traditionally, all < script > elements should be placed in the < head > element of the page
-
But now scripts are usually written on the body element followed by the off tag
- When the browser parses HTML documents, it will parse and display them line by line from top to bottom according to the document flow. JS is a part of HTML, so the execution order of JS script is also determined according to the writing position of < script >
- As a best practice, we will introduce JavaScript code before closing the body tag. In this way, the browser will parse and display HTML before loading the script, which is conducive to improving the performance of the page
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>JS Introduction of</title> </head> <body> <script> alert(1); </script> <script src="./demo1.js"></script> </body> </html>Copy to clipboardErrorCopied
< script > element attribute
- src: optional. Represents the external file that contains the code to execute.
- Type: optional, usually text/javascript. The default script type of modern browsers is JavaScript, so type can be omitted
-
External file js file
- JS programs can not only be written directly in HTML documents, but also in JavaScript files. The suffix is js. It can be edited using any text editor.
- JS files cannot be run alone and need to be imported into web pages using < script > tags.
- The < script > tag defining src attribute should no longer contain JavaScript code, otherwise only external JavaScript files will be downloaded and executed, and the embedded code will be ignored.
<script src="./demo1.js"></script>
Delayed execution of JS defer
- The < script > tag has a Boolean attribute defer. The purpose of this attribute is to indicate that the script will not affect the construction of the page during execution, that is, the script will be delayed until the whole page is parsed.
- Therefore, setting the defer attribute in the script element is equivalent to telling the browser to download immediately, but delaying execution
- If there are multiple delay scripts in the page, the first delay script will execute before the second delay script, and these scripts will execute before the DOMContentLoaded event
- It is applicable to external JS files, not to scripts contained in script tags
//Externally imported js file alert("External introduction js+defer");Copy to clipboardErrorCopied <!-- Look at the running results 1.head introduce js 2.body End introduction js 3.External introduction js+defer --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="./01.js" defer></script> <script> alert("head introduce js") </script> </head> <body> <script> alert("body End introduction js") </script> </body> </html>Copy to clipboardErrorCopied
Load JS file async
- By default, all web pages load external JavaScript files synchronously. When importing external js files, dom execution will be blocked. For this reason, in html4.0 01 introduced async attribute for script tag
- Now you can set the async attribute for the < script > tag and let the browser load Javascript files asynchronously, which means that the script should be downloaded immediately, but it should not hinder other operations of page summary. Valid only for external script files.
- Asynchronous script should not modify DOM during loading. Asynchronous script language must be executed before the load event of the page, but may be executed before or after the DOMContentLoaded event (listening event for DOM rendering completion) is triggered.
- Because it is executed immediately after downloading, the sequence of multiple loading cannot be guaranteed. Therefore, it is ensured that asynchronous scripts do not depend on each other
<!-- The following code is in network Visible in test --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <link href="http://libs.baidu.com/bootstrap/3.0.3/css/bootstrap.css" rel="stylesheet"> <link href="http://cdn.staticfile.org/foundation/6.0.1/css/foundation.css" rel="stylesheet"> <script async src="http://lib.sinaapp.com/js/angular.js/angular-1.2.19/angular.js"></script> <script async src="http://libs.baidu.com/backbone/0.9.2/backbone.js"></script> <script async src="http://libs.baidu.com/jquery/2.0.0/jquery.js"></script> </head> <body> <ul> li*1000 individual </ul> </body> </html>Copy to clipboardErrorCopied
async&defer
-
script with no properties set
The HTML file will be parsed until the script file is downloaded. At the same time, it will stop parsing and initiate a request to extract the script file (if it is an external file). After downloading and executing, HTML parsing will be resumed.
-
The defer attribute is set
Setting the defer attribute will download the script at the same time of HTML parsing, and execute the file after HTML parsing and script downloading. At the same time, the scripts with defer will be executed in the order they appear in the document.
-
async property set
Setting the async property downloads the script file during HTML parsing and pauses the HTML parser to execute the file after the download is complete.
Basic debugging code
alert()
- JavaScript statements are commands sent to browsers. The purpose of these commands is to tell the browser what to do
- The alert() statement causes the browser to pop up a window, and the content in the window is the content in alert()
alert(125); alert("Dashuaibi"); var sex = "girl"; alert(sex);Copy to clipboardErrorCopied
console.log()
-
console.log can print out the information you want to see
-
Contains warnings, errors, and script printouts for the browser
console.log("hello world");Copy to clipboardErrorCopied
document.write() method
- You can insert your incoming content into the HTML output stream, and the browser will parse and display the HTML elements in turn.
- It should be noted that if the document is loaded (that is, the HTML output has been completed), then use document The write () method requires the browser to parse your content, and the browser will rewrite the whole document, resulting in the final document The output of the write () method will overwrite all the previous contents
js basic morphology
-
Case sensitive
JavaScript is strictly case sensitive. In order to avoid input confusion and syntax errors, it is recommended to write code in lowercase characters. Capital letters can be used in the following special cases:
- The first letter of the constructor is recommended to be capitalized
- If the identifier consists of more than one word, consider using camel Nomenclature - the first letter of the following word is capitalized except the first word
-
identifier
-
Identifiers refer to the names of variables, functions, attributes, or parameters of functions.
-
Identifier naming is standardized
-
The first character must be a letter, underscore () Or a dollar sign ($), and other characters can be letters, underscores, dollar signs or numbers
-
Cannot contain spaces. Cannot be named with keywords or reserved words
keyword break do instanceof typeof case else new var catch finally return void continue for switch while debugger* function this with default if throw delete in try top Reserved word abstract enum int short boolean export interface static byte extends long super char final native synchronized class float package throws const goto private transient debugger implements protected volatile double import public yield implements package public interface private static let protected
-
-
notes
A comment is a string of characters that are not parsed. There are two ways to annotate JavaScript
-
Single line note:
//I'm the single line comment shortcut Ctrl + / copy to clipboard errorcopied
-
Multiline comment:
/* I'm multi line comment shortcut ctrl+shift+/ */Copy to clipboardErrorCopied
-
-
sentence
-
Statements in JS are marked with a semicolon; ending
//Valid statements may cause problems -- not recommended var sum = a + b //Valid statements -- recommended var sum = a + b; //Semicolons can be omitted at the end of curly braces -- recommended function sum(a,b){return a + b}Copy to clipboardErrorCopied
-
-
variable
- The variable is equivalent to the container, the value is equivalent to the things contained in the container, and the variable name is the label attached to the container. Through the label, you can find the variable so that you can read and write its stored value
- Code for a memory area. Through this code, the program can save the corresponding type of data to this memory area to complete the requirements of relevant calculations
- ECMAScript variables are loosely typed (weak type, dynamic type). The so-called loose type can be used to save any type of data. In other words, each variable is just a placeholder for holding values
- Using variables can easily obtain or modify the data in memory
-
Use of variables
- Syntax: var keyword + variable name = data. The data to the right of the equal sign assigns a value to the variable name to the left of the equal sign
- In a var statement, you can declare one or more variables or assign values to variables. Unassigned variables are initialized to undefined values. When declaring multiple variables, comma operators should be used to separate them
- In JavaScript, you can declare the same variable repeatedly or initialize the value of the variable repeatedly
var name = "xiaowang"; var sex = "female" , age = 18; var sex2 ; var sex3 , age2; var sex4 , age3 = 19; console.log(sex,age); var score = 100; score = 120; console.log(score); var score = 150; console.log(score);Copy to clipboardErrorCopied
-
Characteristics of JS variable types
JavaScript is a weakly typed language, and the specification for variable types is relatively loose. The specific performance is as follows.
- The type classification of variables is not rigorous and unclear, resulting in the randomness of use.
- When declaring a variable, it is not required to specify a type.
- The use process is not strict, and the variable type can be automatically converted as needed.
- There is no unified and standardized method for variable conversion and type inspection, which leads to low development efficiency
-
Variable pollution
There are three ways to define global variables:
- Directly declare with var statement outside any function.
-
Add attributes directly to global objects. In the Web browser, the global scope object is window
- Using undeclared variables directly, global variables defined in this way are called implicit global variables.
Global variables are visible in the global scope, so they are polluting. Extensive use of global variables will reduce the reliability of the program, and users should avoid using global variables
-
practice
Value exchange between two variables
//The common practice is to declare one more temporary variable tmp for caching during data exchange. This approach is intuitive and easy to understand. Memory usage will increase, however. var a = 1, b = 2, tmp; tmp = a; a = b; b = tmp; //Arithmetic operation, through the skills in the process of arithmetic operation, the two values can be exchanged skillfully. However, one disadvantage is variable data overflow. Because the precision range that JavaScript can store numbers is - 253 to 253. Therefore, there will be overflow in addition operation. var a = 1, b = 2; a = a + b; // a = 3, b = 2 b = a - b; // a = 3, b = 1 a = a - b; // a = 2, b = 1 //Other methods can be learned later ~
Interview practice
-
What is JavaScript
- JavaScript is a literal script language, which is a dynamic type, weak type and prototype based language
- Its interpreter is called JavaScript engine, which is part of the browser,
- Used on HTML web pages to add dynamic functions to HTML web pages.
-
js composition
- ECMAScript: syntax specification
- DOM: document object model operation document
- BOM: Browser Object Model operations browser
-
Please draw and analyze the difference between the normal external introduction of js and defer async attributes
- Default: when js is imported from outside, it will stop parsing html, start downloading js and parse js
- defer: when js is introduced from outside, js will be downloaded asynchronously (without interrupting html parsing). When all html parsing is completed, js will be executed in order
- async: when js are imported from outside, js will be downloaded asynchronously (without interrupting html parsing). However, once a js is downloaded first, html parsing will be stopped immediately and the current js will be executed
-
Analyze undefined types
-
Undefined type:
- There is only one value, undefined
- It usually appears when we are wrong, not the result of our deliberate writing
-
An undefined scenario appears:
- Variable declaration not assigned
- The argument required by the function is not passed as an argument
- When getting a property that an object does not have
- If the function does not return a value, it returns undefined
-
-
Let's talk about identifiers
Identifier:
-Own name, variable name, function name, attribute name, parameter name
Identifier naming conventions:
-Must start with a letter underscore$
-It can be followed by numbers, letters and underscores$
-No spaces are allowed
-Keywords and reserved words cannot be used
-The general requirements shall comply with the small hump writing method
JS data type
Data type - declare variable exercise
// Declare a variable a with the value: 3 // Declare a variable b with a value of null // Declare a variable c with the value: "Hello!" // Declare a variable d with the value: true // Declare a variable e without assignment // Declare a variable f with the value '' var a = 3; var b = null; var c = "hello"; var d = true; var e ; var f = ""; var g = [1,2,3,4];//array var h = function(){};//function
typeof operator
We need a means to detect the data type of a given variable:
- Typeof is the operator responsible for providing this information. The format is typeof (a) or typeof a;
- Sometimes the typeof operator returns confusing but technically correct values
- Classify null as an Object type, not as a special value
- Classify the Function as a Function type, not a subclass of Object type
//Detect the variables of the previous case console.log(typeof a);//number console.log(typeof (b));//object console.log(typeof (c));//string console.log(typeof (d));//boolean console.log(typeof (e));//undefined console.log(typeof (f));//string console.log(typeof (g));//object console.log(typeof (h));//function
Data type classification
- JS data types are divided into two types: simple value (original value) and complex data structure (generally referred to as object).
- Simple values include strings, numbers, and Boolean values. There are also two special values, null and undefined
- Objects include narrow objects, arrays, and functions
data type explain null Null value indicates non object undefined Undefined value,Indicates an unassigned initialization value nunber number,Value of mathematical operation string Character thing,Represents information flow boolean Boolean value,Value of logical operation object Object. A dataset representing a composite structure
Undefined type
What is undefined
- The undefined type has only one value, undefined. For example, when a variable is declared with var but not initialized, the value of this variable is undefined.
- We don't set undefined for a value. Generally, we print it only when there is an error
Common scenarios
-
When a variable is declared but not assigned, it is equal to undefined
//When printing a, it finds a but cannot find the value of a, so an undefined is returned var a; console.log(a); console.log(a+1);//undefined+1 cannot be calculated //Do not declare b, use b directly, js directly report error referenceerror: b is not defined //It indicates that b is not found at all. The variable code reports an error and stops running console.log(b)Copy to clipboardErrorCopied
-
When calling the function, the parameter that should be provided is not provided, and the parameter is equal to undefined
// The declaration function uses the function keyword, and the function will not be executed without calling function add(a,b) { console.log(a) console.log(b) alert(a+b); } // Calling function name + () pass in parameter add(1,2); //Call the function again (not enough parameters given) add(1);Copy to clipboardErrorCopied
-
The object has no assigned attribute, and the value of this attribute is undefined
// Create an object var yourGirlFriend={ name:"lily", age:18, length:180 } // console.log(yourGirlFriend.name); console.log(yourGirlFriend.color);Copy to clipboardErrorCopied
-
When the function does not return a value, it returns undefined by default
function reduce(a,b) { // The function has no return value as long as it does not write return alert(a-b); // return a-b;// Return to a-b } // Function call var num1=reduce(4,2); console.log(num1) console.log(reduce(4,1));Copy to clipboardErrorCopied
-
Check whether a variable is initialized. If not, assign a value to it
var a; if(typeof a === 'undefined'){ a = 10; } console.log(a);
Null type
What is null
- Null type is the second data type with only one value, and this special value is null.
- From a logical point of view, a null value represents a null object pointer, which is why using the typeof operator to detect null returns "object"
Common environment
-
As a parameter of a function, it means that the parameter of the function is not an object
function fn(a,b) { alert(a+b); } // We need to pass parameters, but we don't want to pass them for the time being, or we don't need to pass them, so we can pass an empty object null fn(null,null) /*ajax There is a method send (). The send method parameter is the value you want to pass to the server But the get method splices values in the address bar, so it doesn't need to be passed by send, so we write a parameter null in send and tell him I don't want to pass it here*/Copy to clipboardErrorCopied
-
As the end of the object prototype chain
//For example: "123" -- > string "-- > object" -- > nullcopy to clipboard errorcopied
-
If the defined variable is intended to be used to save objects in the future, it is best to initialize the variable to null instead of other values
var a = null; function fn1() { a=2; } fn1(); console.log(a);
undefined and null
- Undefined is derived from Null. Both of them represent vacancy values. When converted to Boolean values, they are false and can be equal
- But Undefined and Null are two different types
- Undefined implies an unexpected null value, while null implies an expected null value. Therefore, it is recommended to use null instead of undefined when setting a variable and parameter to be null
Number type
What is the Number type
Number s are also called numbers or numbers
- Integer, floating point value (digital direct quantity)
- Octal number (010, 025)
- Hexadecimal number (0xa, 0x1c)
- Binary number
- Scientific counting method
- Number.MIN_VALUE
- Number.Max_VALUE
- Infinity
- NaN
Integer, floating point value (digital direct quantity)
When the number appears directly in the program, it is called digital direct quantity JS. All numbers are stored in 64 bit floating-point numbers, so 2 and 2.0 are the same number
var num1 = 19;//integer console.log(num1); var num2 = 18.11112;//Floating point number console.log(num2);Copy to clipboardErrorCopied
Octal number
The number is preceded by a 0, which represents an octal number
var num3 = 010;//The number preceded by a 0 represents an octal number console.log(num3);//Printed in decimal 8copy to clipboard errorcopied
Hexadecimal number
The number preceded by 0x represents a hexadecimal number
var num4 = 0xff;//The number preceded by 0x represents a hexadecimal number console.log(num4);//255Copy to clipboardErrorCopied
Binary number (poor support, use with caution)
A number preceded by 0b represents a binary number
var num5 = 0b11;//A number preceded by 0b represents a binary number console.log(num5);//3Copy to clipboardErrorCopied
Scientific counting method
E represents the base 10, followed by the exponent of E, which can be positive or negative
//E represents the base 10, and the exponent followed by e can be positive or negative var num5 = 1.2E-7; console.log(num5);//1.2E-7 console.log(num5+1);//After 1.00000012 operation, it becomes a direct quantity display copy to clipboard errorcopied
Max min
In js, numbers are also supported by maximum and minimum values. If the maximum or minimum value is exceeded, the calculation may be wrong
// In js, numbers are also supported by maximum and minimum values. If the maximum or minimum value is exceeded, the calculation may be wrong console.log(Number.MIN_VALUE);//The 5e-324 supports the minimum number console.log(Number.MAX_VALUE);//1.7976931348623157e+308 supports the maximum value of numbers copy to clipboard errorcopied
Infinity
- If the calculation is out of range, you will get infinity or infinitesimal (- infinity)
- A denominator of 0 constitutes Infinity or negative Infinity infinity
- For the operation of infinity, it is impossible to calculate addition, subtraction, multiplication and division. A number is infinity. Infinity and infinity are calculated. Addition and multiplication are infinity and others are NaN
- Infinity is equal to itself, others are normal
// A denominator of 0 constitutes Infinity or negative Infinity infinity var num6 = 5/0; console.log(num6);//Infinity var num7 = -5/0; console.log(num7);//-Infinity console.log(typeof (Infinity));//Both infinity and infinitesimal are of type number // For the operation of infinity, it is impossible to calculate addition, subtraction, multiplication and division. A number is infinity. Infinity and infinity are calculated. Addition and multiplication are infinity and others are NaN console.log(Infinity + 1);//Infinity console.log(Infinity - 1);//Infinity console.log(Infinity - 1000000000000000000000);//Infinity console.log(Infinity - Infinity);//NaN console.log(Infinity * Infinity);//Infinity console.log(Infinity + Infinity);//Infinity console.log(Infinity / Infinity);//NaN //Infinity is equal to itself, and others are normal console.log(Infinity > 1);//true console.log(Infinity < 1);//false console.log(Infinity == 1);//false console.log(Infinity > Infinity);//false console.log(Infinity == Infinity);//true console.log(Infinity < Infinity);//false console.log(Infinity > -Infinity);//trueCopy to clipboardErrorCopied
NaN
- NaN, or not a number, is a special value
- This value is used to indicate that an operand that is supposed to return a value does not return a value (so that an error will not be thrown)
- aN features: no matter who you compare with, it is fasle, and no matter who you calculate with, it is NaN
var num8 = "Li Peihua"-1; console.log(num8)//NaN // NaN features: no matter who you compare with, it is fasle, and no matter who you calculate with, it is NaN console.log(NaN+1);//NaN console.log(NaN>1);//fasle console.log(NaN==1);//fasle console.log(NaN<1);//fasleCopy to clipboardErrorCopied
Use of isNaN method
- The isNaN method detects whether a value is a non pure number. If it is a non pure number, it returns true. If it is a pure number, it returns false
- Case: when clicking detection, judge whether it is all numbers
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>isNaN</title> </head> <body> Please enter your phone number: <input id="ipt" type="text"> <button id="btn">testing</button> <script> /* * 1,Click the button (bind the click event to the button) * 2,Get the value ss of input * 3,Using isNaN detection * 4,Judge whether the detected value is true or false * 5,If true, the value entered is not a pure number. If false, it is a pure number */ // 0. Get tag /*document((document) . Members access properties or methods in the document get Is to get Element Is element By Yes Id id If the name is not a variable in parentheses, use quotation marks*/ // To get the value, you need to save this element with a variable // The naming rules are that the variable names of DOM elements agree to start with o, and the first letter after it is capitalized var oIpt = document.getElementById("ipt"); var oBtn = document.getElementById("btn"); // 1. When clicking btn, onclick assigns an anonymous function to obtn after the click event onclick // At this time, when you click btn, the function will execute oBtn.onclick=function () { //2 get the value of input and save it with variables var userCon = oIpt.value; // 3. Judge whether it is a pure number. If isTrue is true, it contains other characters. If false, it is a pure number var isTrue = isNaN(userCon); //4. Judge and execute // If isTrue is true, the pop-up will pop up. Please re-enter, otherwise the pop-up input is correct if (isTrue == true) { alert("Please re-enter"); }else{ alert("Correct input"); } } /*// The optimization of the above code is as follows var oIpt = document.getElementById("ipt"); var oBtn = document.getElementById("btn"); oBtn.οnclick=function () { if (isNaN(oIpt.value)) { alert("Please re-enter ""); }else{ alert("Enter correct ""); } }*/ </script> </body> </html>Copy to clipboardErrorCopied
Floating point overflow
- When performing numerical calculation, prevent floating-point number overflow. For example, 0.1 + 0.2 is not equal to 0.3
- Problems caused by js executing binary floating-point arithmetic standard.
- Solution: the certificate operation of floating-point number is accurate, so the problem of eliminating performance can be avoided by specifying accuracy. For example, (1 + 2) / 10
Number method of type conversion
The Number() method converts other types to Number type, and the Number method returns a converted value
// 1. Number to number or the original value // 2. String to number console.log(Number(""));//0 empty string -- > 0 console.log(Number(" "));//0 is a string of spaces -- > 0 console.log(Number("123"));//0 is a string of pure numbers -- > corresponding numbers console.log(Number("1a23"));//0 is not a string of pure numbers -- > Nan //3. Boolean to number console.log(Number(true));//1 true-->1 console.log(Number(false));//0 false-->0 // 4. undefined to digital console.log(Number(undefined));//NaN undefined-->NaN // 5. null to number console.log(Number(null));// 0 null--->0 // 6. Object (array and object) to number console.log(Number([]));//0 empty array -- > 0 console.log(Number([1,2,3]));//NaN general non empty array -- > NaN console.log(Number([1]));//The 1 number has only one value and is a number -- > the current number console.log(Number(["1"]));//The 1 number has only one value and is a string of numeric values -- > the current number console.log(Number(["a"]));//The 0 number has only one value and is non numeric -- > Nan console.log(Number({}));//NaN empty object -- > NaN console.log(Number({name:"lily"}));//NaN non empty object -- > nanzcopy to clipboard errorcopied
parseInt() of type conversion
parseInt is a global method that converts values to integers
- Step 1: first analyze the character at position 0. If it is not a valid number, it will directly return NaN.
- Step 2: if the character at position 0 is a number or can be converted to a valid number, continue to parse the character at position 1. If it is not a valid number, directly return the valid number at position 0.
- Step 3, and so on, analyze each character one by one from left to right until non numeric characters are found.
- In step 4, parseInt() will convert all the legal numeric characters analyzed earlier into numerical values and return them.
Note: the point number in a floating-point number is an illegal character for parseInt, so the decimal value will not be converted. If it is a numeric string starting with 0, parseInt() will not treat it as an octal number. If it is a numeric string starting with 0x, parseInt() will treat it as a hexadecimal number: first convert it to a hexadecimal number, and then convert it to a decimal number to return.
parsInt also supports base mode, which can convert numeric strings of different base numbers into integers
console.log(parseInt(123));//123 console.log(parseInt("a123"));//NaN console.log(parseInt("1a123"));//1 console.log(parseInt("10a23"));//10 console.log(parseInt("100px"));//100 console.log(parseInt(12.3));//12 console.log(parseInt("0xa"));//12 console.log(parseInt(null));//NaN console.log(parseInt(true));//NaN /* * parseInt Support base mode to convert numeric strings with different base numbers into integers * */ var a = "abc123"; console.log(parseInt(a,16));//11256099 takes a as hexadecimal and converts it into hexadecimal output var b = "111"; console.log(parseInt(b,2));//7 console.log(parseInt(5,3));//NaN, because there is no 5 in hexadecimal // Special circumstances are as follows: console.log(parseInt(1,1));//NaN console.log(parseInt(0,1));//NaN console.log(parseInt(0,0));//0Copy to clipboardErrorCopied
parseFloat() of type conversion
- parseFloat() is also a global method that converts a value to a floating-point number, that is, it can recognize the first decimal point, and the second decimal point is considered illegal. The parsing process is the same as parseInt.
- The parameter of parseFloat() must be a decimal string, ignoring or returning 0 before hexadecimal and octal.
console.log(parseFloat(123));//123 console.log(parseFloat(12.3));//12.3 console.log(parseFloat("12.3.3"));//12.3 console.log(parseFloat("a12.1"));//NaNCopy to clipboardErrorCopied
Multiplier operator of type conversion
If the variable is multiplied by 1, the variable will be automatically converted into a value by JS. If it cannot be converted into a legal value, NaN will be returned
/* * If the variable is multiplied by 1, the variable will be automatically and implicitly converted to digital type. If it cannot be converted, it will become NaN * */ var a = "1"; console.log(a * 1);//1 of type number var b = "1a"; console.log(b * 1);//NaN /* * Subtraction is OK * */ var c = "1"; console.log(c - 0);//1 of type number var d = "1a"; console.log(d - 0);//NaN /*It's OK to divide by 1*/ var e = "1"; console.log(e / 1);//1 of type number var f = "1a"; console.log(f / 1);//NaN
String type
A JavaScript string is a character sequence consisting of zero or more Unicode characters. Zero characters represent an empty string.
String direct quantity
- The child line string must be enclosed in single or double quotation marks
- If the string is contained in double quotation marks, the string can contain single quotation marks; Conversely, you can also include double quotation marks in single quotation marks
- In ECMAScript 3, the string must be represented in one line, and the newline representation is not allowed. If you want to display the string on a newline, you can add a newline character (\ n) to the string
- In ECMAScript 5, strings are allowed to be represented in multiple lines Implementation method: add a backslash () at the end of the newline Backslashes and line breaks are not used as the contents of the string literal
- To insert special characters into a string, you need to use escape characters, such as single quotation marks, double quotation marks, etc
- Each character in a string has a fixed position The subscript position of the first sub character is 0, the subscript position of the second character is 1,... And so on. The subscript position of the last character is the length of the string minus 1
var str1 = '093284yrc091708)(*&(^&(*&T'; var str2 = "kajhx askjh &*("; var str3 = `9287O&*b`; var str4 = "Xiao Wang said to his mother:'He wants to marry Cuihua to me'"; console.log(str4); var str5 = "Today's weather\n splendid" console.log(str5); var str6 = "Today's weather\ splendid"; console.log(str6); Copy to clipboardErrorCopied
Escape character
-
Escape character is an indirect representation of character. In a special context, the character itself cannot be used directly
var str = "Please look\"This is a double quotation mark"; console.log(str);//See "this is a double quote copy to clipboard errorcopied
-
Some characters with backslash will represent special characters instead of the original character itself. These special escape characters are called escape sequences
\0 Null character (\ u0000)
\b backspace (\ u0008)
\t horizontal tab (lu0009)
\n line feed (lu000A)
\v vertical tab (\ u000B)
\f page feed (\ u000C)
\r carriage return (\ u000D)
-
If you add a backslash before a normal character, JavaScript ignores the backslash
var str = "Xiao Ming's mother said:\"What a nice day today\""; console.log(str);//Xiao Ming's mother said, "it's a nice day today." var str2 = "Xiao Ming's mother said:\"\this\day\day\gas\really\good\""; console.log(str2);//Xiao Ming's mother said, "it's a nice day today." var str3 = "Look at my slash:\\" console.log(str3);//Look at my slash: \ copy to clipboard errorcopied
String operation
-
With the prototype method of String type, you can operate strings flexibly (described in detail in the following chapters)
-
In JavaScript, you can use the plus sign (+) operator to connect two strings
-
Use the length property of the string to get the number of characters (length) of the string
-
In ES5, strings can be used as read-only arrays, and a value can be accessed by adding a subscript through the bracket operator. The subscript starts from 0, and the subscript of the maximum position is length-1
var str = "The teacher said"; var say = "How do you do"; console.log(str+say);//The teacher said hello console.log(str + 1);//The teacher said 1 console.log(str + 1);//The teacher said 1 console.log(1 + 1);//2 console.log("1" + 1);//11 console.log(1 + "1");//11 var str1 = "Today is a fine day 123 b5"; console.log(str1.length);//13 console.log(str1[0]);//this //Get the last character console.log(str1[str1.length-1]);//5Copy to clipboardErrorCopied
String exercises
When the user submits the account and password, judge whether it is correct. The known account is lipeihua and the password is 1234561
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>String practice</title> </head> <body> <!-- When the user submits the account and password, judge whether it is correct. The known account is lipeihua The password is 1234561 --> Please enter the account name: <input type="text" id="user" autofocus> Please input a password: <input type="password" id="pass"> <button id="btn">Sign in</button> <script> /* * 1.Get element * 2.Click event * 3.Judge whether the account is correct (click to get the account password directly) * 4.Determine whether the password is correct * 5.If it is not cleared correctly and re entered correctly, the login success will be returned * */ var oUser = document.getElementById("user"); var oPass = document.getElementById("pass"); var oBtn = document.getElementById("btn"); oBtn.onclick = function () { //Use userUser to save the user name entered by the user when clicking var userUser = oUser.value; //Use userPass to save the password entered by the user when clicking var userPass = oPass.value; // judge if(userUser == "lipeihua"){ if (userPass == 1234561) { alert("Give you a little hair"); }else{ alert("Boy, your password is wrong") oPass.value = ""; oPass.focus(); } }else{ alert("User name error"); // userUser = "";// Never just change the variable, because this is only the re assignment of the variable, and there is no operation on the value value oUser.value = ""; // Get the form into focus oUser.focus(); } } </script> </body> </html>Copy to clipboardErrorCopied
String method
The String method can convert other types to String types
//1. Conversion of null type console.log(String(null));//'null' of string //2.undefined conversion console.log(String(undefined));//'undefined' of string //3. Conversion of number type //Conversion rules: ordinary numbers are directly converted into strings. Other hexadecimals are first converted into hexadecimal, and then into corresponding strings. Both infinity and infinitesimal NaN are directly converted into strings console.log(String(123));//'123' console.log(String(-123));//'-123' console.log(String(010));//'8' console.log(String(0xff));//'255' console.log(String(4E-5));//'0.00004' console.log(String(Infinity));//'Infinity' console.log(String(-Infinity));//'-Infinity' console.log(String(12.3));//'12.3' console.log(String(NaN));//'NaN' //4. Boolean conversion console.log(String(true));//'true' console.log(String(false));//'false' //5. Object conversion console.log(String([]));//Empty string '' console.log(String([1]));//'1' console.log(String([1,2,3]));//'1,2,3' console.log(String({}));//[object object] console.log(String({name:"lily"}));//[object object]Copy to clipboardErrorCopied
toString() method
-
When there is a + (plus sign) operator in our code, it will call the toString() method to convert other types of things into strings, and then splice them with the original string into a string
-
Except for null and undefined, other types (numeric, Boolean, string, object) have toString() method, which returns the string representation of the corresponding value (without modifying the original variable).
-
Each object has a toString() method.
-
Called automatically when the object is represented as a text value, or when an object is referenced as an expected string.
(1).toString() // "1" [1,2].toString() // "1, 2" ({}).toString() // [object Object] true.toString() // "true" null.toString() // Uncaught TypeError: Cannot read property 'toString' of null undefined.toString() // Uncaught TypeError
Boolean type
Boolean types contain only two fixed values: true and false. Where true stands for true and false for false.
In some operations such as judgment, Boolean values need to be used
Boolean method of type conversion
//1,null console.log(Boolean(null));//false //2.undefined console.log(Boolean(undefined));//false //3.number //The number to Boolean value is not 0. It is true. 0 is false. Nan is false console.log(Boolean(123));//true console.log(Boolean(-123));//true console.log(Boolean(0));//false console.log(Boolean(1.23));//true console.log(Boolean(NaN));//false console.log(Boolean(Infinity));//true console.log(Boolean(010));//true console.log(Boolean(0xa));//true //4.string //true is not empty console.log(Boolean("123"));//true console.log(Boolean(""));//false console.log(Boolean(" "));//true //5.object //Object types are converted to true console.log(Boolean([]));//true console.log(Boolean([1,2,3]));//true console.log(Boolean([0]));//true console.log(Boolean({}));//true console.log(Boolean({name:"lily"}));//trueCopy to clipboardErrorCopied
Dual logic of type transformation
A logical non operator (!) You can convert a value to a Boolean value and reverse it. The two are to convert it to the correct Boolean value
console.log(!!0); Copy to clipboardErrorCopied
Boolea n exercise
When clicking the button, when the input is empty, the input border will turn red, otherwise it will be black
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Boolean type</title> <style> #ipt{ border:1px solid #000; } </style> </head> <body> <input type="text" id="ipt"> <button id="btn">Button</button> <script> /* * When clicking the button, when the input is empty, the input border will turn red, otherwise it will be black * */ var oBtn = document.getElementById("btn"); var oIpt = document.getElementById("ipt"); oBtn.onclick = function () { var oIptValue = oIpt.value; //First judgment oIptValue = = "" //The second judgment oiptvalue length == 0 //The third judgment directly uses if, which can be implicitly converted if(oIptValue){//oIptValue is not empty oIpt.style.borderColor = "#000"; }else{//oIptValue is null // Change the inline style of elements oIpt.style.borderColor = "red"; } } </script> </body> </html>
JS operator
Boolean types contain only two fixed values: true and false. Where true stands for true and false for false.
In some operations such as judgment, Boolean values need to be used
Boolean method of type conversion
//1,null console.log(Boolean(null));//false //2.undefined console.log(Boolean(undefined));//false //3.number //The number to Boolean value is not 0. It is true. 0 is false. Nan is false console.log(Boolean(123));//true console.log(Boolean(-123));//true console.log(Boolean(0));//false console.log(Boolean(1.23));//true console.log(Boolean(NaN));//false console.log(Boolean(Infinity));//true console.log(Boolean(010));//true console.log(Boolean(0xa));//true //4.string //Null is false and non null is true console.log(Boolean("123"));//true console.log(Boolean(""));//false console.log(Boolean(" "));//true //5.object //Object types are converted to true console.log(Boolean([]));//true console.log(Boolean([1,2,3]));//true console.log(Boolean([0]));//true console.log(Boolean({}));//true console.log(Boolean({name:"lily"}));//trueCopy to clipboardErrorCopied
Dual logic of type transformation
A logical non operator (!) You can convert a value to a Boolean value and reverse it. The two are to convert it to the correct Boolean value
console.log(!!0); Copy to clipboardErrorCopied
Boolea n exercise
When clicking the button, when the input is empty, the input border will turn red, otherwise it will be black
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Boolean type</title> <style> #ipt{ border:1px solid #000; } </style> </head> <body> <input type="text" id="ipt"> <button id="btn">Button</button> <script> /* * When clicking the button, when the input is empty, the input border will turn red, otherwise it will be black * */ var oBtn = document.getElementById("btn"); var oIpt = document.getElementById("ipt"); oBtn.onclick = function () { var oIptValue = oIpt.value; //First judgment oIptValue = = "" //The second judgment oiptvalue length == 0 //The third judgment directly uses if, which can be implicitly converted if(oIptValue){//oIptValue is not empty oIpt.style.borderColor = "#000"; }else{//oIptValue is null // Change the inline style of elements oIpt.style.borderColor = "red"; } } </script> </body> </html>
comma operator
Assignment operator
Multiplicative operator
Addition Operator
concept
practice
Increment decrement operator
Relational operation
Size comparison
Equality and congruence
Logical operation
And
or
wrong
practice
Short circuit principle
Unary operation
Summary of string to number method
Ternary operator
Judgmental optimization
Operator precedence
Comprehensive practice
JS statement
What statement
- ECMA-262 specifies a set of process control statements. Statement defines the main syntax in ECMAScript. Statements usually complete a given task by one or more keywords. Such as judgment, circulation, exit, etc.
- Statements are mainly divided into declaration, branch control, loop control, process control, exception handling, etc.
Declaration statement
There are three kinds of declaration statements: declaration variables, declaration functions and declaration labels
// Declaring a function uses the function keyword function f() {} // Declare variable var a = 1;//The declared promotion scope is calculated according to the function let b = 2;//Undeclared promotion scope is calculated according to code block const MAX = 100;//Undeclared promotion constants cannot be modified or reassigned // Declaration Label: // Declaration statements are generally used in conjunction with continue and break, which will be explained in the following process control statements for1: for (var i = 0;i<3;i++){ }
Debug statement
- The debugger statement is used to stop JS
- The debugger statement can be used to close any breakpoint in the script file, but it will not be placed in any similar position in the code
for (var i = 0; i < 5; i++) { debugger; console.log(1); }
if statement
Single branch
- Writing format: if (judgment) {code block}
- If the judgment is true, the code block is executed.
- The judgement does not have to write various operators. No matter what is passed in, if will convert it into a Boolean value and then execute the if code
- if statements are usually used (when..., otherwise...)
- if the code block of the judgment statement is a single sentence, we can omit braces (but it is not recommended in js)
//[single branch if] declare variables A and b, and assign values a and b equal to 5; When a equals b, re assign b to 10 and pop up the new value of b var a = 5 , b = 5 ; // If a is not equal to b, the entire if will not be executed because there is no else // js allows you to write only if but not else if ( a == b ){ b = 10; alert(b); }
Double branch
- Else statements are executed only when the conditional expression of an if or else/if statement is false.
- if (judgment) {code block 1}else {code block 2}
- If the judgment is true, execute statement 1, otherwise execute statement 2
//[double branch] declare that variable a is assigned 100; When a is greater than 50, "a is really big" pops up; otherwise, "a is really small" pops up var a = 100; if (a > 50){ alert("a How big"); }else{ alert("a It's so small"); } //[double branch] y value is related to x value. When x is greater than or equal to 3, the y value is 2. When x is less than 3, the y value is 1 var y = 4,x = 2; if (x >= 3){ y = 2; }else{ y = 1; } //[double branch] if x is greater than y, then x value is y value plus 1, otherwise x value is y value minus 1 var x = 3,y = 4; if (x > y){ x = y + 1; }else{ x = y - 1; } //[double branch] if x is greater than y or X is less than z, then the value of X is the value of z; otherwise, the value of X is the value of Y var x = 1,y = 2,z = 3; if (x > y || x < z) { x = z; }else{ x = y; }
else if statement
- else if statements can form multiple branches
- If (conditional expression) {statement 1;} else if (conditional expression) {statement 2;} Else {statement 3;}
// [multi branch] if x value is 3, y value is 2; if x value is greater than 3, y value is 1; if x value is less than 3, y value is 4 var x = 3,y = 4; if (x == 3){ y = 2; }else{ // Enter else if x is not equal to 3 if (x >3){ y = 1; } else{ y = 4; } } //else if() is to continue judging in the remaining conditions based on the last judgment if (x == 3){ y = 2; }else if (x > 3){ y = 1; }else{ y = 4; } //[multi branch] x value is 2 and y value is 1. If x value is smaller than 2, y value is 0. If x value is larger than 10, y value is 10. If x value is less than 4 and greater than 3, y value is 5. In other cases, y value is 3 var x = 2, y = 1; if (x < 2){ y = 0; }else if (x >10){ y = 10; }else if(x < 4 && x > 3){ y = 5; }else{ y = 3; }
practice
Lao Li document~
-
HTML
-
CSS
-
HTML5
-
CSS3
-
JavaScript Foundation
-
JS statement
-
JavaScript DOM
-
JavaScript advanced
-
JS common interview questions
-
jQuery
-
Less
-
ES5
-
ES6
-
Git tutorial
-
GitHub use
-
NodeJS
JS statement
What is a statement
- ECMA-262 specifies a set of process control statements. Statement defines the main syntax in ECMAScript. Statements usually complete a given task by one or more keywords. Such as judgment, circulation, exit, etc.
- Statements are mainly divided into declaration, branch control, loop control, process control, exception handling, etc.
Declaration statement
There are three kinds of declaration statements: declaration variables, declaration functions and declaration labels
// Declaring a function uses the function keyword function f() {} // Declare variable var a = 1;//The declared promotion scope is calculated according to the function let b = 2;//Undeclared promotion scope is calculated according to code block const MAX = 100;//Undeclared promotion constants cannot be modified or reassigned // Declaration Label: // Declaration statements are generally used in conjunction with continue and break, which will be explained in the following process control statements for1: for (var i = 0;i<3;i++){ }Copy to clipboardErrorCopied
Debug statement
- The debugger statement is used to stop JS
- The debugger statement can be placed anywhere in the code to abort the execution of the script, but it will not close any files or delete variables, similar to setting breakpoints in the code
for (var i = 0; i < 5; i++) { debugger; console.log(1); }Copy to clipboardErrorCopied
if statement
Single branch if
- Writing format: if (judgment) {code block}
- If the judgment is true, the code block is executed.
- The judgement does not have to write various operators. No matter what is passed in, if will convert it into a Boolean value and then execute the if code
- if statements are usually used (when..., otherwise...)
- if the code block of the judgment statement is a single sentence, we can omit braces (but it is not recommended in js)
//[single branch if] declare variables A and b, and assign values a and b equal to 5; When a equals b, re assign b to 10 and pop up the new value of b var a = 5 , b = 5 ; // If a is not equal to b, the entire if will not be executed because there is no else // js allows you to write only if but not else if ( a == b ){ b = 10; alert(b); }Copy to clipboardErrorCopied
Double branch else statement
- Else statements are executed only when the conditional expression of an if or else/if statement is false.
- if (judgment) {code block 1}else {code block 2}
- If the judgment is true, execute statement 1, otherwise execute statement 2
//[double branch] declare that variable a is assigned 100; When a is greater than 50, "a is really big" pops up; otherwise, "a is really small" pops up var a = 100; if (a > 50){ alert("a How big"); }else{ alert("a It's so small"); } //[double branch] y value is related to x value. When x is greater than or equal to 3, the y value is 2. When x is less than 3, the y value is 1 var y = 4,x = 2; if (x >= 3){ y = 2; }else{ y = 1; } //[double branch] if x is greater than y, then x value is y value plus 1, otherwise x value is y value minus 1 var x = 3,y = 4; if (x > y){ x = y + 1; }else{ x = y - 1; } //[double branch] if x is greater than y or X is less than z, then the value of X is the value of z; otherwise, the value of X is the value of Y var x = 1,y = 2,z = 3; if (x > y || x < z) { x = z; }else{ x = y; }Copy to clipboardErrorCopied
else if statement
- else if statements can form multiple branches
- If (conditional expression) {statement 1;} else if (conditional expression) {statement 2;} Else {statement 3;}
// [multi branch] if x value is 3, y value is 2; if x value is greater than 3, y value is 1; if x value is less than 3, y value is 4 var x = 3,y = 4; if (x == 3){ y = 2; }else{ // Enter else if x is not equal to 3 if (x >3){ y = 1; } else{ y = 4; } } //else if() is to continue judging in the remaining conditions based on the last judgment if (x == 3){ y = 2; }else if (x > 3){ y = 1; }else{ y = 4; } //[multi branch] x value is 2 and y value is 1. If x value is smaller than 2, y value is 0. If x value is larger than 10, y value is 10. If x value is less than 4 and greater than 3, y value is 5. In other cases, y value is 3 var x = 2, y = 1; if (x < 2){ y = 0; }else if (x >10){ y = 10; }else if(x < 4 && x > 3){ y = 5; }else{ y = 3; }Copy to clipboardErrorCopied
Practice of if statement
The user enters the grade and then pops up the grade
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>if Sentence practice</title> </head> <body> Grade (please enter a number): <input type="text" id="ipt"> <p>Grade:<span id="con"></span></p> <script> /* * The user enters the grade and then pops up the grade * The score is > = 90 a > = 80 < 90 b > = 70 < 80 C > = 60 < 70 d other Z */ var oIpt = document.getElementById("ipt"); var oCon = document.getElementById("con"); oIpt.onchange = function () { // Get the value of the form and convert it into a numeric value var userScroe = parseInt(this.value); if (userScroe >= 90){ oCon.innerHTML = "A"; }else if(userScroe >= 80){ oCon.innerHTML = "B"; }else if(userScroe >= 70){ oCon.innerHTML = "C"; }else if(userScroe >= 60){ oCon.innerHTML = "D"; }else{ oCon.innerHTML = "Z"; } } </script> </body> </html>
switch Statements
-
Switch statements are specifically used to design multi branch conditional structures. Compared with else/if multi branch structure, switch structure is more brief and efficient.
-
The syntax is as follows:
switch (expression)
case value1: statement 1; break; case value2: Statement 2; break; ………… default: statement}
- The switch statement compares with the value value of the expression after case once according to the branch of the expression. If they are equal, the subsequent statement segments will be executed, and only break will be encountered, or the switch statement will be terminated. If you don't want to wait, continue to find the next case.
- The switch statement contains an optional default statement (exception handling of switch). If the previous case does not find an equal condition, the default statement will be executed, which is similar to the else statement.
- The switch statement uses congruence (= = =) to detect whether two are equal. So there will be a comparison of value types
- case can be followed by an empty statement, which puts multiple conditions together for detection
- In the switch statement, the case clause only indicates the starting point of execution, but does not indicate the end point. If there is no break statement after the case, continuous execution will occur, ignoring the conditional restrictions of the subsequent case.
var a = 6; switch (a) { case 1: alert(1); // break; case 2: alert(2); // break; case 3: alert(3); // break; case 4: alert(4); break; case 5: case 6: case 7: alert(8); break; default: alert(10) }Copy to clipboardErrorCopied
-
practice
The user enters the grade and then pops up the grade
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>switch practice</title> </head> <body> Please enter grade (number): <input type="text" id="ipt"> <p>Grade:<span id="con"></span></p> <script> /* * The user enters the grade and then pops up the grade * The score is 100 -- > s > = 90 a > = 80 < 90 b > = 70 < 80 C > = 60 < 70 d other Z */ var oIpt = document.getElementById("ipt"); var oCon = document.getElementById("con"); oIpt.onchange = function(){ //Get the score entered by the user var userScore = this.value; // Because switchdo is equal, we take the first place in all scores, and then judge the equality. For example, all scores above 90 start with 9 userScore = parseInt(userScore / 10); switch (userScore) { case 10: oCon.innerHTML = "S"; break; case 9: oCon.innerHTML = "A"; break; case 8: oCon.innerHTML = "B"; break; case 7: oCon.innerHTML = "C"; break; case 6: oCon.innerHTML = "D"; break; default: oCon.innerHTML = "D"; } } </script> </body> </html>
Circular statement
In program development, there are a lot of repetitive operations or calculations, which must be completed by loop structure. JS provides three types of loop statements: while for do/while.
while Loop
-
The while statement is the most basic loop structure. The syntax format is as follows:
While (judgment){
sentence
}
-
When the judgment is true, execute the statement. After execution, judge again until the judgment formula is false, and then jump out of the loop.
// Use the while() loop to calculate 1 + 2 + 3+ 98 + 99 + 100. var i = 1; var num = 0; while(i <= 100){ num += i; i ++; } console.log(num); // You can also add an increment to a circular statement var i = 1; var num = 0; while(i++ <= 100){ num += i; } //During each execution, the conditions should be changed, otherwise it will enter the dead cycle var a = 4; while(a < 7){ console.log(a); a ++ ; } // Find out the multiple of 3 between 1-100 and print it var i = 1; while(i <= 100){ if (i % 3 == 0){ console.log(i); } i++; }
do...while
-
do/while is very similar to while loops, except that the value of the expression is checked at the end of each loop rather than at the beginning.
do{
sentence
}While (judgment formula)
-
Because the do/while loop can ensure that the loop is executed at least once. While is not necessarily.
//Basic use var a = 3; do{ console.log("hello"); }while(a < 1); // Use the do while() loop to calculate 1 + 2 + 3+ Value of 98 + 99 + 100: var i = 1; var num = 0; do{ num += i; i ++; }while(i <= 100); console.log(num)
practice
Calculate annual interest rate
Users enter a number of money, and the annual interest rate is 1.05 (the interest and capital of last year are the principal of the next year). It takes several years to double
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Calculate annual interest rate</title> </head> <body> <input type="text" id="ipt"> <script> /* * Users enter a number of money, and the annual interest rate is 1.05 (the interest and capital of last year are the principal of the next year). It takes several years to double */ var oIpt = document.getElementById("ipt"); var scale = 1.05; oIpt.onchange = function () { var userMoney = parseFloat(this.value); var fatalMoney = 2 * userMoney; var years = 0; //When the user's money is less than doubled, the loop will be executed all the time while(userMoney <= fatalMoney){ // In the circular body, the principal is increased by 1.05 times every time, and it is circulated once a year userMoney *= scale; //Increase the number of years by 1 for each cycle years ++; } alert("You need to double your money"+years+"year"); } </script> </body> </html>
Judge login
For the account and password entered by the user, as long as the account is not laowang and the password is not 88888, we always prompt you to re-enter, otherwise it is proposed that the input is successful
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Judge login</title> </head> <body> <script> // Prompt is a pop-up window containing confirmation and cancellation of the input box. The value entered by the user is the return value of the prompt method. If the user does not enter or the input is empty, null will be returned //The first parameter of prompt is to prompt the user //Method 1 //1. Just after entering the page, a window pops up to let the user enter the account name and password var userName = prompt("enter one user name"); var passWord = prompt("Please input a password"); //2. If the judgment is incorrect, you will always ask the pop-up to enter the account name and password, so you can consider the while loop while(userName != "laowang" || passWord != "88888"){ // 3. If the password is entered incorrectly or the account number is entered incorrectly, enter the while execution pop-up window userName = prompt("enter one user name"); passWord = prompt("Please input a password"); } alert("Welcome to Lao Wang") // Method 2: recursive call var userName = prompt("enter one user name"); var passWord = prompt("Please input a password"); //Because you have to judge after each input, you need to encapsulate a function function isLogin() { if (userName != "laowang" || passWord != "88888"){ userName = prompt("enter one user name"); passWord = prompt("Please input a password"); isLogin();//Recursive algorithm (calling itself in function) }else{ alert("Welcome to Lao Wang. Are you Lao Wang") } } isLogin(); </script> </body> </html>
for statement
practice
-
The for statement is a more concise loop structure
for (expression 1; expression 2; expression 3)
Statement 1;
Statement 2;
}
Statement 3
-
Expression 1 is evaluated unconditionally once before the start of the loop, while expression 2 is evaluated before the start of each loop. If the value of expression 2 is true, the loop statement is executed, otherwise the loop is terminated. Expression 3 is evaluated after each cycle and then judged again.
/* for Loop execution sequence 1,Execute statement 1 first 2,Execute judgment 2. If it is true (return true), execute the code block. If it is not true (return false), the whole loop ends 3,If the judgment is true and the code block is executed, statement 3 will be executed after the code block is executed 4,After the execution of statement 3, execute judgment 2 again 5,Repeat the second step */ // Suppose you pop up 5 times in total for (var i = 0; i < 5; i++) { console.log("nei hao a"); } // Exercise: define a variable a=5, let a execute 5 times, and add 3 each time. Then pop up a final value. var a = 5; for (var i = 0; i <5 ; i++) { a += 3; } console.log(a);
Practice of for loop
- Find the sum of 1 to 9
- Find the sum of 1 to 100
- Find the sum of singular numbers in 1-99
- Find the sum of numbers in 1-99 that are multiples of 3
- Define a v. When v is equal to 0, v adds 1 three times. Otherwise, v conduct 4 times of self adding 2
- Define v = 3; Traverse the variable i from 0 to 3; When i is equal to 2, V adds 2; Otherwise, V will add 3
//1. Find the sum of 1 to 9 // 1+2+3+4+5+6+7+8+9 // Define a variable to save and default to 0 var num = 0; for (var i = 1; i < 10; i++) { num += i; } console.log(num); // 2. Find the sum of 1 to 100 var num = 0; for (var i = 1; i < 101; i++) { num += i; } console.log(num); // 3. Find the sum of singular numbers in 1-99 var num = 0; for (var i = 1; i < 100; i+=2) { num += i; } console.log(num) // 4. Find the sum of numbers in 1-99 that are multiples of 3 var num = 0; for (var i = 3; i < 100; i+=3) { num += i; } console.log(num) var num = 0; for (var i = 0; i < 100; i++) { if (i % 3 == 0){ num += i; } } console.log(num) // 5. Define a v. When v is equal to 0, v adds 1 three times. Otherwise, v conduct 4 times of self adding 2 var v = 3; if(v == 0){ for (var i = 0; i <3 ; i++) { v++; } }else{ for (var i = 0; i <4 ; i++) { v += 2; } } // 6. Define v = 3; Traverse the variable i from 0 to 3; When i is equal to 2, V adds 2; Otherwise, V will add 3 var v = 3; for (var i = 0; i < 4; i++) { if (i == 2){ v += 2; }else{ v += 3; } }Copy to clipboardErrorCopied
Application of for loop
For all li binding click events, click who makes whose background color turn red
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>for Cyclic application</title> </head> <body> <ul id="box"> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> </ul> <script> /* * Effect on all li binding click events, click who makes whose background color turn red * 1,Get tag */ // 1. Get tag var oBox = document.getElementById("box"); var oLis = oBox.getElementsByTagName("li"); /*oLis[0].onclick = function () { this.style.backgroundColor = "red"; } oLis[1].onclick = function () { this.style.backgroundColor = "red"; } oLis[2].onclick = function () { this.style.backgroundColor = "red"; } oLis[3].onclick = function () { this.style.backgroundColor = "red"; } oLis[4].onclick = function () { this.style.backgroundColor = "red";sd }*/ /* for (var i = 0; i < oLis.length; i++) { oLis[i].onclick = function () { this.style.backgroundColor = "red"; } }*/ /* * Effect on even number of (0 2 4 6 8 10) li binding click events, click who makes whose background color turn red * 1,Get tag */ var oBox = document.getElementById("box"); var oLis = oBox.getElementsByTagName("li"); for (var i = 0; i < oLis.length; i += 2) { oLis[i].onclick = function () { this.style.backgroundColor = "red"; } } </script> </body> </html>Copy to clipboardErrorCopied
99 multiplication table
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>99 multiplication table</title> </head> <body> <div id="box"> </div> <script> var oBox = document.getElementById("box"); for (var i = 1; i < 10; i++) { // The first for control line for (var j = 1; j <= i; j++) { // The second for executes the sign multiplier of this line var math = j + "*" + i + "=" + j*i+" "; console.log(math) oBox.innerHTML = oBox.innerHTML + math; } // At the end of each line execution, a new line is added oBox.innerHTML += "<br>"; } </script> </body> </html>
Process control
Using break, label, continue and return statements can change the flow direction of branch structure and loop structure halfway to improve the execution efficiency of the program. Return will be explained in detail in the function.
label statement
- In JS, the label statement can add labels to one line of statements to facilitate the setting of jump targets in complex structures.
- The syntax is as follows: label: statement
- Label can be any legal identifier, and then use colon to separate label name and label statement.
- label and break statements are used together. They are mainly used in circular structure and multi branch structure to jump out of the inner nested body.
var num=0; outermost: for(var i=0; i<10;i++){ for(var j=0; j<10; j++){ if(i==5 && j==5){ break outermost; } num++; } } console.log(num);
break statement
- The break statement can end the execution of the current for, for/in, while, do/while or switch statement. At the same time, break can accept an optional tag name to determine the structure statement to jump out.
- If the tag name is not set, the current innermost structure will jump out.
//break is the code that immediately exits the loop or exits after the switch statement executes the loop var num =0 ; for ( var i=0 ; i<5 ; i++ ) { if ( i == 3 ) { break; } num++; } alert( num ); var num=0; outermost: for(var i=0; i<10;i++){ for(var j=0; j<10; j++){ if(i==5 && j==5){ break outermost; } num++; } } console.log(num);
continue Statement
- The continue statement is used in the loop structure to jump out of the remaining code in this loop and continue to execute the next loop when the value of the expression is true.
- You can accept an optional tag name to determine the loop statement to jump out.
var num =0 ; for ( var i=0 ; i<5 ; i++ ) { if ( i == 3 ) { continue; } num++; } alert( num ); var num=0; outermost: for(var i=0; i<10;i++){ for(var j=0; j<10; j++){ if(i==5 && j==5){ continue outermost; } num++; } } console.log(num);Copy to clipboardErrorCopied
practice
- Find the accumulated value of integers 1 ~ 100, but stop accumulating if it is required to encounter a number with bit 3
- Find the cumulative value of integers 1 ~ 100, but it is required to skip all numbers with 3 bits
- Find the sum of integers between 1 and 100 that cannot be divided by 7 (use continue)
- Find the sum of all odd numbers between 200-300 (use continue)
- Find the first number between 200-300 that can be 7 integer (break)
exception handling
ECMA-262 specifies seven error types. Error is the base class, and the other six error types are subclasses, which inherit the base class. The main function of error type is to customize the error object.
- Error: normal exception. Used with thorw statement and try/catch statement, the attribute name can read and write exception types, and the message attribute can read and write detailed error information.
- EvalError: thrown when the eval() method is used incorrectly
- Syntax error: thrown when a syntax error occurs
- RangeError: thrown when the number exceeds the legal range
- Error thrown when reading a variable that does not exist: Reference
- TypeError: thrown when the type of the value is wrong
- URIError: thrown when URI encoding and decoding errors occur
try/catch/finally statement
-
The try/catch/finally statement is an exception handling statement
try{
Debug code block
}
catch(e){
A block of code that captures exceptions and handles them
}
finally{
Post cleanup code block
}
-
Normally, JS executes the code in the try clause in order. If no exception occurs, it will ignore the catch and jump to the finally clause to continue execution.
-
If you run an Error in the try clause or use the throw statement to actively throw an exception, execute the code in the catch clause and pass in a parameter to reference the Error object
// try catch case try{ console.log(a);//When an error occurs in try, it will directly enter catch for execution console.log("I am try"); }catch (e) { console.log("catch"); console.log(e);//referenceError:a is not defined console.log(e.name);//referenceError console.log(e.message);//a is not defined } try{ console.log("try"); throw new Error("Are you not defining variables"); }catch (e) { console.log("catch") console.log(e); console.log(e.name); console.log(e.message); } try{ console.log("try"); // throw new Error("did you not define a variable"); }catch (e) { console.log("catch") console.log(e); console.log(e.name); console.log(e.message); }finally { console.log('finally') } alert(1); // throw is an error thrown var a = 10; if(a > 4){ // throw "are you wrong?"; // throw new TypeError("your type error"); var userError = "You made a mistake today. The mistakes are as follows........"; throw new SyntaxError(userError); }
Sentence practice
Cashier procedure
ATM key
Buy insurance
Cashier procedure
Enter the unit price and quantity to calculate the total price. 20% off if the total price is more than 500. Then the user enters the payment, and finally the change pops up.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Cashier procedure</title> </head> <body> <script> //Enter the unit price and quantity of the item var price = prompt("Please enter the unit price"); var count = prompt("Please enter quantity"); //Calculate the total price var sumPrice = price * count; //Judge whether to discount if (sumPrice >= 500){ sumPrice *= 0.8; } //Tell the user how much they need to pay var money = prompt("Your current consumption"+sumPrice+"Yuan, please pay(Just enter the denomination of the payment. I'll give you the change later)"); // Judge whether the user's payment is sufficient and give change if (money > sumPrice) { // Calculate change var reduceMoney = money - sumPrice; alert("give change" + reduceMoney + "Yuan, please keep it") }else{ alert("The money is not enough!!!!") //At this time, you can call recursively again, and the code is omitted } alert("looking forward to your next visit"); </script> </body> </html>Copy to clipboardErrorCopied
ATM key
Enter the corresponding number and perform the corresponding function
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>ATM Key</title> </head> <body> <script> var userPress = prompt("Welcome to the bank, please enter the number selection function (1.Query balance, 2.Withdraw money, 3.Transfer, 4.(exit)"); switch (parseInt(userPress)) { case 1: search(); break; case 2: drag(); break; case 3: change(); break; case 4: exit(); break; default: alert("Can't you understand the hint"); } function search() { alert("Querying balance"); } function drag(){ alert("I'm withdrawing money"); } function change() { alert("Transfer in progress") } function exit() { alert("Exiting") } </script> </body> </html>Copy to clipboardErrorCopied
Buy insurance
The company buys insurance for employees (users can check whether they meet the conditions through this program): 1 As long as you get married; 2. Unmarried men under the age of 25 do not buy; 3. Unmarried girls under the age of 22 do not buy it
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Buy insurance</title> </head> <body> <script> /* * The company buys insurance for employees (users can check whether they meet the conditions through this program): * As long as you get married * Unmarried men under the age of 25 do not buy * Unmarried girls under the age of 22 do not buy */ //Enter whether to get married var isMarry = prompt("Are you married? Please enter yes and no"); var age = prompt("How old are you this year"); var sex = prompt("What is your gender(man or woman)"); if (isMarry === "yes"){ alert("You can rest assured that the company will provide you with free insurance"); }else if ((sex === "man" && age < 25) || (sex === "woman" && age < 22)){ alert("Go home and buy it yourself"); }else{ alert("The company also buys it for you"); } </script> </body> </html>
JS function
Cashier procedure
Enter the unit price and quantity to calculate the total price. 20% off if the total price is more than 500. Then the user enters the payment, and finally the change pops up.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Cashier procedure</title> </head> <body> <script> //Enter the unit price and quantity of the item var price = prompt("Please enter the unit price"); var count = prompt("Please enter quantity"); //Calculate the total price var sumPrice = price * count; //Judge whether to discount if (sumPrice >= 500){ sumPrice *= 0.8; } //Tell the user how much they need to pay var money = prompt("Your current consumption"+sumPrice+"Yuan, please pay(Just enter the denomination of the payment. I'll give you the change later)"); // Judge whether the user's payment is sufficient and give change if (money > sumPrice) { // Calculate change var reduceMoney = money - sumPrice; alert("give change" + reduceMoney + "Yuan, please keep it") }else{ alert("The money is not enough!!!!") //At this time, you can call recursively again, and the code is omitted } alert("looking forward to your next visit"); </script> </body> </html>Copy to clipboardErrorCopied
ATM key
Enter the corresponding number and perform the corresponding function
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>ATM Key</title> </head> <body> <script> var userPress = prompt("Welcome to the bank, please enter the number selection function (1.Query balance, 2.Withdraw money, 3.Transfer, 4.(exit)"); switch (parseInt(userPress)) { case 1: search(); break; case 2: drag(); break; case 3: change(); break; case 4: exit(); break; default: alert("Can't you understand the hint"); } function search() { alert("Querying balance"); } function drag(){ alert("I'm withdrawing money"); } function change() { alert("Transfer in progress") } function exit() { alert("Exiting") } </script> </body> </html>Copy to clipboardErrorCopied
Buy insurance
The company buys insurance for employees (users can check whether they meet the conditions through this program): 1 As long as you get married; 2. Unmarried men under the age of 25 do not buy; 3. Unmarried girls under the age of 22 do not buy it
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Buy insurance</title> </head> <body> <script> /* * The company buys insurance for employees (users can check whether they meet the conditions through this program): * As long as you get married * Unmarried men under the age of 25 do not buy * Unmarried girls under the age of 22 do not buy */ //Enter whether to get married var isMarry = prompt("Are you married? Please enter yes and no"); var age = prompt("How old are you this year"); var sex = prompt("What is your gender(man or woman)"); if (isMarry === "yes"){ alert("You can rest assured that the company will provide you with free insurance"); }else if ((sex === "man" && age < 25) || (sex === "woman" && age < 22)){ alert("Go home and buy it yourself"); }else{ alert("The company also buys it for you"); } </script> </body> </html>
JS object
What is an object
js, any value can be converted into an object and used as an object
Define object
Constructor
Object direct quantity
Using object and create
Operation of object properties
Attributes are also called name value pairs, including attribute names and attribute values. Two attributes with the same name cannot exist in one attribute. Attribute values can be any type of data.
Define attributes
Direct quantity definition
Point syntax definition
Bracket syntax
Use object defineProperties
Read attribute
Delete attribute
Control object status
Traversal of objects
Basic and reference types
concept
Basic type value
Reference type value
What is an object
- js, any value can be converted into an Object and used as an Object, such as digital Object, Boolean Object, string Object, type Object, function Object, array Object, etc. they all inherit Object type objects and share common basic properties and methods.
- In addition, JavaScript also allows user-defined objects. In a narrow sense, an object is the most basic data type. It is a composite structure and reference data. It is an unordered data set, and each member in the object is called an attribute.
Define object
Constructor
- Use the new operator to call the constructor to construct an instance object. The specific usage is as follows: var objectName = new functionName (args)
- The parameters are described below
- objectName: returned instance object
- functionName: constructor, which is basically the same as ordinary functions
- args: instance object initialization configuration parameter list
var num1 = new Number(111); console.log(num1); var obj = new Object({ name:1 }); console.log(obj);Copy to clipboardErrorCopied
Object direct quantity
- Using direct quantity can quickly define objects, and it is also the most efficient and simple method. var objectName = {attribute name 1: attribute value 1, attribute name n: attribute value}
- In the object direct quantity, the attribute name and attribute value are separated by colons. The attribute value can be any type of data. The attribute name can be a JavaScript identifier or a string expression. The attributes are separated by commas. There is no need for commas at the end of the last attribute.
- If the attribute value is an object, you can design an object with a nested structure
- If it does not contain any attributes, you can define an empty object
var obj1 = { name:"lily", "sex":"female", score:[100,90,80,12,35,34], fri:{ fir1:"xiaowang", fir2:"xiaoli", fir3:{ sis1:"dahua", sis2:"xiaohua", sis3:["zhangdama","zhangxiaoma","zhangma"] } } } console.log(obj1.sex);Copy to clipboardErrorCopied
Using Object create
-
Object.create is a new static method in ECMAScript5, which is used to define an instance object.
-
This method can specify the prototype and object properties of the object. The specific usage is as follows
object.create (prototype, descriptors)
- Prototype: must be a parameter. Specify the prototype object. It can be null
- Descriptoroptional parameter, a JavaScript object that contains one or more property descriptors. The attribute descriptor includes data characteristics and accessor characteristics, and the data characteristics are described as follows
- Value: Specifies the attribute value
- Writable: the default value is false. Set whether the attribute value is writable
- Enumerable: the default value is false. Set whether the attribute is enumerable (for/in)
- C onfigurable: the default value is flse, which sets whether attributes can be modified or deleted
- The accessor feature contains two methods. The brief description is as follows: set(): set the property value, and get(): return the property value
//Object.create method var obj = {}; console.log(obj); var obj2 = Object.create(obj1); console.log(obj2);//Empty object but inherits obj1 console.log(obj2.name);//It doesn't matter. His father does //Create a clean object var obj3 = Object.create(null); console.log(obj3); //Create an object var obj4 = Object.create(null,{ name:{ value:"xiaowang", writable:true, enumerable:true, }, sex:{ value:"nv" } }) console.log(obj4); console.log(obj4.name); obj4.name = "laowang"; console.log(obj4); for(i in obj4){ console.log(i); } //Accessor properties var obj5 = Object.create(null,{ a:{ value:"hello", writable:true }, b:{ get:function () { return this.a+" world" }, set:function (i) { this.a = i + "I'm late"; } } }) console.log(obj5); console.log(obj5.b);//When a property is called, the get of its accessor property will be accessed, and the return value of the get method is the value of b obj5.b = "hahaha";//When setting the property, the set method of the accessor will be called, and the set value is the parameter of the method console.log(obj5);Copy to clipboardErrorCopied
Operation of object properties
Attributes are also called name value pairs, including attribute names and attribute values. Two properties with the same name cannot exist in an object. The value of an attribute can be any type of data
Define attributes
Direct definition
In the object direct quantity, attribute names and attribute values are separated by colons. The left side of the colon is the attribute name, the right side is the attribute value, and name value pairs (attributes) are separated by commas.
//Use direct quantity definition var obj1 = { name:"laowang", sex:"male" }; var obj2 = new Object({ name:"xiaowang", sex:"nv" }) var obj3 = Object.create(null,{ name:{ value:"dawang", writable:true }, sex:{ value:"nan" } }) Copy to clipboardErrorCopied
Point syntax definition
//Point syntax definition: var obj4 = { name:"xiaozhang" } obj4.sex = "nan"; console.log(obj4); var obj5 = new Object({ name:"xiaowang", sex:"nv" }) obj5.age = 20; console.log(obj5); var obj6 = Object.create(null,{ name:{ value:"dazhang", writable:true, } }) obj6.age = 10;//You can also directly set properties on the object created by create, but you cannot select the properties of the properties. By default, they can be modified and enumerated console.log(obj6); obj6.age = 20; console.log(obj6); for(var i in obj6){ console.log(i); }Copy to clipboardErrorCopied
Bracket syntax
var obj7 = { name:"xiaowang" } var a= "sex" obj7[a] = "nv"; obj7["sex"] = "nv"; console.log(obj7); function getMess(obj,pro) { return obj[pro] } var myself = {name:"huahua",sex:"nan",age:"19"}; console.log(getMess(myself, "sex"));Copy to clipboardErrorCopied
Object.defineProperty
Use object The defineproperty function can add properties to an object or modify existing properties. If the specified attribute name does not exist in the object, perform the add operation; if there is an attribute with the same name in the object, perform the modify operation
// Object.defineProperty(obj,pro,{}) var obj8 = { name:"xiaoli" } Object.defineProperty(obj8,"sex",{ value:"nv", }); Object.defineProperty(obj8,"name",{ //If you modify the original name attribute value, it can be modified and enumerated value:"dali", }); console.log(obj8); for(var i in obj8){ console.log(i); }Copy to clipboardErrorCopied
Use object defineProperties
- You can define multiple attributes at once
- Object.defineProperties(object,description)
- Object: the object to which attributes are added or modified, which can be a local object or a DOM object
- description: contains one or more descriptor objects. Each descriptor object describes a data attribute or accessor attribute
var obj9 = { like:"miantiao" } Object.defineProperties(obj9,{ color:{ value:"yellow", enumerable:true }, length:{ value:"10m", } }) console.log(obj9);Copy to clipboardErrorCopied
Read attribute
Use point syntax
You can quickly read and write object attributes using point syntax. The left side of point syntax is the variable of the reference object, and the right side is the attribute name.
var obj1 = { name:"xiaowang", like:"Singing and dancing rap Basketball", time:"Two and a half years" } console.log(obj1.name)Copy to clipboardErrorCopied
Use bracket syntax
- Structurally, objects are similar to arrays, so you can use brackets to read and write object properties
- In bracketed syntax, the property name must be specified as a string, and identifiers cannot be used.
- You can use a string or a character expression in brackets, that is, as long as the value of the expression is a string
// Case for in traversal rewrite var obj1 = { name:"xiaowang", like:"Singing and dancing rap Basketball", time:"Two and a half years" } for(var item in obj1){ console.log(item); obj1[item] = obj1[item] + "@"; } console.log(obj1);Copy to clipboardErrorCopied
Object.getOwnPropertyNames
- Use object The getownpropertynames function can return the name of the private property of the specified object.
- Private properties refer to user-defined properties locally, not inherited prototype properties.
var obj1 = { name:"xiaowang", like:"Singing and dancing rap Basketball", time:"Two and a half years" } console.log(Object.getOwnPropertyNames(obj1));//["name","like","time"]Copy to clipboardErrorCopied
Use object keys
Use object The keys() function can only obtain the enumerable private attribute names, and the return value is an array containing the enumerable attribute names of the object
Object.getOwnPropertyDescriptor()
- Can get the descriptor of the object property
- Object.getOwnPropertyDescriptor(object,propertyname)
- The parameter object represents the specified object, propertyname represents the name of the property, and the return value is the descriptor object of the property
//Set the properties of the object created by the create method var obj2 = Object.create(null,{ name:{ value:"Xinbao Island", enumerable:true }, time:{ value:"5min", enumerable:true }, like:{ value:"rap" } }) console.log(Object.getOwnPropertyNames(obj2));//["name","like","time"] console.log(Object.keys(obj2));//["name","time"] console.log(Object.getOwnPropertyDescriptor(obj1, "like"));//{value: "rap basketball @", writable: true, enumerable: true, configurable: true} console.log(Object.getOwnPropertyDescriptor(obj2, "time"));//{value: "5min", writable: false, enumerable: true, configurable: false} Copy to clipboardErrorCopied
Delete attribute
Use the delete operator to delete the attribute of the object. After deleting the attribute of the object, the attribute value is not set to undefined, but the attribute is completely cleared from the object
var obj = { name:"laowang", sex:"nan", like:undefined } console.log(obj.like);//You can set an attribute value to undefined console.log(Object.getOwnPropertyNames(obj));//Property names set to undefined values can still be obtained delete obj.sex;//Delete a property console.log(obj); console.log(Object.getOwnPropertyNames(obj));//When a property is deleted, its property name cannot be enumerated. Copy to clipboard errorcopied
Control object status
- Object.preventExtensions(): prevents adding new properties to objects
- Object.seal(): prevents adding new attributes to the object and cannot delete old attributes. It is equivalent to setting the configurable attribute of the attribute description object to false. Note that this method does not affect modifying the value of an attribute
- Object. Free (): prevent adding new attributes, deleting old attributes and modifying attribute values for an object, and provide three corresponding auxiliary check functions at the same time
- Object.isExtensible(): check whether an object allows adding new attributes
- Object.isSealed(): check whether an object uses object Seal method
- Object.isFrozen(): check whether an object uses object Free method
// 1.Object.preventExtensions(): var obj = { name:"xiaoxinxin", width:"200", height:"300" } console.log(obj); obj.color = "red";//Set new properties console.log(obj); console.log(Object.isExtensible(obj)); Object.preventExtensions(obj);//Prevent setting new properties console.log(Object.isExtensible(obj)); obj.bg = "green"; console.log(obj);//New properties cannot be set after blocking // 2.Object.seal(): var obj2 = { name:"dadudu", width:"200", height:"300" } console.log(obj2); delete obj2.width;//Delete an old attribute console.log(obj2); console.log(Object.isSealed(obj2)); Object.seal(obj2)//Prevent adding new attributes and deleting old attributes console.log(Object.isSealed(obj2)); delete obj2.height; console.log(obj2); // 3.Object.freeze() var obj3 = { name:"xiaowangba", width:"200", height:"300" } console.log(obj3); obj3.width = "1000";//Modify old properties console.log(obj3); console.log(Object.isFrozen(obj3)); Object.freeze(obj3); console.log(Object.isFrozen(obj3)); obj3.height = "800"; console.log(obj3);Copy to clipboardErrorCopied
Traversal of objects
- The for in loop is dedicated to traversing objects
- The variables defined in for in represent the key name of the object
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Traversal of objects</title> </head> <body> <script> var person = { headTeacher:{ name:"Sister Xiao Ning", sex:"20", age:"nv", method:"headmaster" }, jobTeacher:{ name:"Lili", sex:"22", age:"nv", method:"obtain employment" }, bossTeacher:{ name:"Lao Tan", sex:"50", age:"male", method:"principal" } } console.log(person.length);//The attribute of defined object is not defined function teacherMessage(obj) { alert("My name is"+obj.name); alert("My age is"+obj.age); alert("My gender is"+obj.sex); alert("My role is"+obj.method); } // The for in loop is dedicated to traversing objects // The variables defined in for in represent the key name of the object for(var i in person){ // console.log(i); teacherMessage(person[i]); } </script> </body> </html>Copy to clipboardErrorCopied
Basic and reference types
concept
- Data types are divided into five simple data types and one complex data type, which correspond to basic type value and reference type value respectively
- Basic type value: null undefined string number boolean
- Reference type value: object (regular, array, object, function...)
- What kind of classification: it is classified according to the different storage methods of these two values
Basic type value
- Basic type value: null undefined string number boolean
- Basic type values are the actual values stored in variables by direct operation of accessing by value
- The basic type values are stored in the stack area, and we can access the actual value directly through the variable name
var num1 = 10;//Open a space in the stack area. The name of the stack area is the variable name, and the value of the stack area is the value corresponding to this variable var num2 = num1; //Reopen an area, save the value of num2, obtain the value of num1 and assign it to num2 num1 = 30;//The value of num2 in stack area is 30, but it will not change console.log(num1,num2);//30 10Copy to clipboardErrorCopied
- Characteristics of basic type value:
- The value of the base type is immutable
- We can't add properties and methods to basic type values, even if we add them, we can't get them
- The comparison of basic types is the comparison of values
- Basic type variables are stored in the stack area (stack area refers to the stack memory in memory). The stack area includes the identifier and value of the variable
// 1. The value of the base type is immutable /*Add a value to the array, or the original array. If the basic type value changes, it will no longer be the original value for a long time, but will be re assigned. Therefore, we cannot change the value of the basic type, otherwise we will change the value directly */ // 2. We can't add properties and methods to basic type values, even if we add them, we can't get them var str1 = "abc"; str1.eat = "apple";//An attribute eat is extended to the base type str1.say = function () {//Extend a method to a base type value alert("You talk"); } console.log(str1.eat);//undefined str1.say();//str1.say is not a function // 3. The comparison of basic types is the comparison of values var num1 = 5; var num2 = null; console.log(num1 < num2);//The comparison of basic type values is to take out the value corresponding to the variable for comparison. Take it out first and then convert it for type comparison // 4. Basic type variables are stored in the stack area (stack area refers to the stack memory in memory). The stack area includes the identifier and value of the variable Copy to clipboardErrorCopied
Reference type value
- The reference type value stack stores the identifier (variable name) and reference address, and the heap stores the value of the object
- When we access an object, we must first access the address of the stack area, and then reference the value of the heap area
var obj1 = { name:"lily" }//Declare an object, and then the value is saved in the heap area, and the variable and reference address are saved in the stack area var obj2 = obj1;//The assignment is the reference address of the stack area, and the address of obj1 is assigned to obj2 obj1.name = "lucy";//Changed the content of obj1 heap object value console.log(obj1,obj2);//The reference addresses of obj1 and obj2 are the same, so they point to the same object copy to clipboard errorcopied
- Reference type value characteristics:
- The value of the reference type is variable. We can add properties and methods to the reference type
- The value of a reference type is an object stored in both stack memory and heap memory
- The comparison of reference types is the comparison of references
// 1. The value of the reference type is variable. We can add properties and methods to the reference type var arr1 = [1,2,3]; arr1.say = function () { alert("How do you do"); } arr1.say(); // 2. The value of a reference type is an object stored in both stack memory and heap memory //3. The comparison of reference types is the comparison of references var obj1 = {}; var obj2 = {}; console.log(({} == {}));//false although the two objects are empty
JS array
What is an array
Define arrays and read / write arrays
Construct array
Array direct quantity
Multidimensional array
Empty array
Associative array
Pseudo class array
Fibonacci sequence
Length of array
Operation array
Stack operation
Queue operation
Delete element
pop() and shift()
Deletes the last and first values of the array and returns the deleted elements of the array
length attribute
As long as the length attribute is set and the length is smaller than the original array, all elements outside the new array will be deleted
delete
The array element at the specified subscript position can be deleted. The deleted element is a null element, and the deleted array length remains unchanged
splice: delete some values of the array. You can delete one or more array elements (number) after the specified subscript position
-Parameter 1:
-Parameter 2:
var arr=[1,2,3,4,5,6,7,8]; var re=arr.pop(); console.log(arr,re); arr.length=4; condole.log(arr); delete arr[1];//Just delete the value and keep the position console.log(arr); arr.splice(1);//Where to start deleting arr.splice(3,0);//From which position to delete, delete several elements, and return the deleted elements into a new array cosole.log(arr);
Add element
push and unshift
Insert elements into the back or front end of the array. You can insert multiple elements at the same time and return the length of the modified array
Using the subscript method, you can directly add elements to the array or modify some values of the array
Concat: merge arrays. Add all concat parameters to the tail of the array and directly return the merged new array
concat can have multiple parameters and can be merged together
The concat parameter enables the array to be expanded and merged into the arr, and only one dimension can be expanded
splice: adds some values anywhere in the array
Parameter 1: the position to start deletion. If it is a negative number, whether to search backwards, length or backward
Parameter 2: delete length. The length is a negative number. The default value is 0
Parameter 3: delete the element added at the position, so that any number of values can be added
effect:
Delete: parameter 1 and parameter 2
Add: parameter 1 is the subscript to be added, and parameter 2 should be set to 0 in length to add a new element
Replace: parameter 1 is the added subscript, parameter 2 is the length to be replaced, and parameter 3 is the added new element, which can be of any length
var arr=[1,2,3,4,5,6,7]; var re=arr.push(1); console.log(re,arr); arr[arr.length]="a"; cosole.log(arr); var arr=[1,2,3,4,5]; var re=arr.concat(1); var re=arr.concat(1,2) var re=arr.concat([1,2]); var re=arr.concat([1,[1,2]],[3,4]); console.log(arr,re); var arr=[1,2,13,4,56,7,8,9]; console.log(arr); arr.splice(2,0,"a"); console.log(arr); console.log(re);
splice() method
Delete: parameter 1 and parameter 2
Add: parameter 1 is the subscript to be added, and parameter 2 should be set to 0 in length to add a new element
Replace: parameter 1 is the added subscript, parameter 2 is the length to be replaced, and parameter 3 is the added new element, which can be of any length
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-phxhtnyn-1619244581188) (C: \ users \ Juan ~ er \ appdata \ roaming \ typora user images \ image-20210329104041832. PNG)]
slice() method
Intercepting the array, deleting the array and returning the intercepted new array
Parameter 1: the position of starting interception (subscript), which is generally not negative
Parameter 2: end position (not included). If the end position is negative, it is inverted
var arr=[1,2,3,4,5,4,6,7,8,9]; console.log(arr); arr.slice(3,6);//Intercepting the array has no effect on the original array var arr=[1,21,3,4,56,89,7,8,9]; var re=arr.slice(3,-1); console,log(arr); console.log(re); var str1="[object Object]"; var str1="[object String]"; var str1="[object Null]"; var str1="[object Boolean]"; var str1="[object Undefinde]"; str1.slice(8); str1.slice(8,-1);
Array sorting
sort() method
Changed the original array and returned the address value of the original array
If there are no parameters, it will be sorted in ascending order by default, and will be converted to string for comparison by default (string comparison is a bit-by-bit comparison)
var arr=[1,22,44,66,88,77,99,11]; var re=arr.sort(arr); console.log(arr); console.log(re);
Common: sort receives a callback function, that is, the parameter is a function
The parameters of the callback function are two (receive two parameters), and two numbers are compared each time
If the rutuen function is negative, the position will be exchanged. If the return function is other, the position will not be exchanged
The first parameter and the second parameter of the callback function represent the following value and the previous value respectively (why not the following value and the previous value, it's strange)
return a-b is in ascending order
return b-a is in descending order
var arr=[1,22,55,44,99,77,33,88]; arr.sort(funtion(a,b){ //Compare two adjacent data at a time //Here is the comparison of calling functions /* console.log(a,b); return -1;*///First trigger from here, inspire ideas, and then think about and write the following code console.log(a,b); /* return a-b;*///It can be replaced by the following function segment code (a single statement here can be converted into the following code segment function, and the writing method can be extended) if(a>b){ return 1; }else if(a<b){ return -1; }else{ return 0; } })//If you change the value of return to negative, the effect will change console.log(arr);
reverse() method
Array reverse output
Directly change the original array and return the address value of the original array
Can be reversed
var arr=[1657,554,68,486,54,697,788]; var re=arr.reverse(arr); console.log(arr); console.log(re);
Array conversion
toString()
toLocalString()
join()
Element positioning
indexof()
lastIndexof()
Check whether all elements comply with
every() method
Check for compliance
some() method
for iterative array
forEach
Iterating with keys
Mapping array
Array filtering
reduce
Array method summary
Array exercise
Summary of array de duplication methods
- Method 1: push and pop methods are combined with double-layer for loop nesting
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Array de duplication</title> </head> <body> <script> //Define an array var arr=[1,2,3,3,2,6,9,5,4,5,9,34]; //The new array is used to store var newArr=[]; //The for loop iterates through the current array for(var i=0;i<arr.length;i++){ newArr.push(arr[i]); for(var j=0;j<=i;j++){ if(arr[i]==arr[j]&&i!=j){ newArr.pop(arr[i]); } } } console.log(arr); console.log(newArr) </script> </body> </html>
Operation results:
[the external chain image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (IMG wihhnkav-1619244581188) (C: \ users \ Juan ~ er \ appdata \ roaming \ typora \ typora user images \ image-20210408025013875. PNG)]
- Method 2: sort() method combined with for loop, push()
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Method 2</title> </head> <body> <script> //Define an array var arr=[1,2,3,3,2,6,9,5,4,5,9,34]; //The new array is used to store var newArr=[]; console.log("Initial array:"+arr); arr.sort(); console.log("Sorted array:"+arr); for(var i=0;i<arr.length;i++){ if(arr[i-1]!=arr[i]){ newArr.push(arr[i]); } } console.log("Array after de duplication:"+newArr); </script> </body> </html>
Operation results:
[the external chain image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-e0nmv7dc-1619244581189) (C: \ users \ Juan ~ er \ appdata \ roaming \ typora user images \ image-20210408030829901. PNG)]
- Method 3:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Method 3</title> <!--indexOf--> </head> <body> <script> //Define an array var arr=[1,2,3,3,2,6,9,5,4,5,9,34]; //The new array is used to store var newArr=[]; console.log(arr); for(var i=0;i<arr.length;i++){ //Determine the first occurrence of the current element in the array, and insert the current element into the new array // if(newArr.indexOf(arr[i])===-1){ // newArr.push(arr[i]) // } //Determine the first occurrence of the current element in the array, and insert the current element into the new array ----- 2 if(arr.indexOf(arr[i])===i){ newArr.push(arr[i]) } } console.log(newArr); </script> </body> </html>
- Method 4:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Method 4</title> <!--lastIndexOf--> </head> <body> <script> //Define an array var arr=[1,2,3,3,2,6,9,5,4,5,9,34]; //The new array is used to store var newArr=[]; console.log(arr); for(var i=0;i<arr.length;i++){ newArr.lastIndexOf(arr[i])!==-1?'':newArr.push(arr[i]); } console.log(newArr); </script> </body> </html>
Method 5:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Method 5</title> </head> <body> <script> //Define an array var arr=[1,2,3,3,2,6,9,5,4,5,9,34]; console.log(arr); //The new array is used to store console.log(arr); var newArr=[]; var len=arr.length; for(var i=0;i<len;i++){ for(j=i+1;j<len;j++){ if(arr[i]==arr[j]){ arr.splice(j,1); len--; j--; } } } </script> </body> </html>
JS string
Basic package type
- To facilitate the operation of simple data types, javascript also provides three special simple types: string/number/boolean
- In fact, whenever a basic type is read, an object of the corresponding basic wrapper type will be created in the background, so that we can call some methods to manipulate the data
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Basic package type</title> </head> <body> <script> var str1="some text"; var sr2=str1.substring(2); //The above process is divided into three steps //1. Create an instance of string type //2. Call the specified method on the instance //3. Destroy this instance var str1=new String("some text"); var str2=str1.substring(2); /* substring()Method introduction: Intercepts the string according to the specified start and end subscripts Parameter 1: start subscript Parameter 2: end subscript (Note: if parameter 2 here is not written, it means the end) * */ str1=null; //Why can't we extend properties or methods to basic types var str="12345"; str.name="nice"; //The analysis is as follows: var _str=new String("12345"); _str.name="nice"; _str=null; /* !!!: for the first time: Although it means something like this (), I think there will still be some problems if I express it orally The second time: I don't understand, ha ha, * * */ </script> </body> </html>
Test:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Test basic package type</title> </head> <body> <script> //Test 1: var str="12345"; console.log(str);//Output: 12345 var str2=str.substring("2"); console.log(str2);//Output: 345 console.log(str);//Output: 12345 //The contents of str are output here. Why is it said that this instance was destroyed //If you create an instance with str, you can destroy it directly //Instead, create the same method to call, and assign the value to str2 after the change? </script> </body> </html>
concat method
- Using the concat method of string, you can add multiple parameters to the tail of the specified string
- There is no limit on the type and number of parameters. All parameters are converted to strings
- Return: string after connection
- In certain cases, you can use addition and array to splice strings
- The join method of the original array replaces the concat method, which is very fast. However, the contemporary tour optimizes the plus sign splicing. Therefore, it is recommended to use a plus sign to splice strings.
// var str1="hello"; // var _str1=str1.concat("world","!"); // console.log(str1);// Output: hello // console.log(_str1);// Output: helloworld! //After splicing here, I think it is not very beautiful, so I think: //When splicing strings, //Solution: this effect can be achieved by adding a space in front of each string spliced // var str1="hello"; // var _str1=str1.concat(" ","world"," ","!"); // console.log(str1);// Output: hello // console.log(_str1);// Output: hello world! // var str2="hello"; // var _str2=str1.concat("world",['oh','nice'],{name:"xiaozhou"}); // console.log(str2);// Output: hello // console.log(_str2);// Output: helloworldoh, nice [object] /* Output result analysis: (Fill in why) * */ //Create a string var straLL = "0123456789abcdefghijklmnopqrstuvwxyz"; //Create an empty array var strArr = []; // for (var i = 0; i < 20; i++) { //floor(): round down //random(): generate random numbers var strNum = Math.floor(Math.random() * straLL.length); strArr.push(straLL[strNum]);//Take the obtained random strNum value as the subscript of the array } var finallyStr = strArr.join(" ");//Add a space at the end of each string console.log(finallyStr);//Print out the final string
String lookup
- charAt(n) returns the nth character in the string. If the parameter is not between 0-length-1, it returns an empty string
- indexOf and lastIndexOf: the subscript position of the specified substring can be returned according to the parameter string. Both methods have two parameters. The first parameter is the search target and the second parameter is the starting position
- The function of the search method is the same as that of indexOf. It finds the position where the specified string appears for the first time, but there is only one parameter to define the matching mode, without reverse retrieval and global mode.
- The Matth method can find all matching substrings and return them in the form of an array. If the matching mode does not specify global, it will be matched once. null if not found
// 01.charAt var str = "hello i am fine thankyou"; console.log(str.charAt(8));//a console.log(str.charAt(0));//a console.log(str.charAt(str.length));//Empty string //02.indexOf() and lastIndexOf() var str = "hello i am fine thankyou"; console.log(str.indexOf("a"));//8 console.log(str.lastIndexOf("a"));//18 console.log(str.indexOf("a",9));//18 console.log(str.lastIndexOf("a",5));//-1 is inverted, and 5 is the subscript // 03.search(); var str = "110p1101h110"; var index1 = str.search(/[a-zA-Z]/g); console.log(index1); // 04.match() var str = "110p1101h110"; var index2 = str.match(/[a-zA-Z]/g); console.log(index2);//["p","h"]
String interception
- Substr method: substr can intercept the substring according to the specified length. It contains two parameters, one is the starting subscript and the other is the intercepted length. Omitting the second parameter represents the end (ECMA no longer recommends this method)
- slice and substring methods intercept the string according to the specified start and end subscripts. They contain two parameters, one is the start subscript, the other is the end subscript (not included), and the omission of the second parameter represents the end
- substring can be used when the size of the start and end positions cannot be determined.
- If it is negative, slice can treat negative values as from right to left. substring is considered invalid
var str = "today is a fine day"; var _str = str.substr(4,5); console.log(str);//today is a fine day console.log(_str);//y is var _str = str.substr(4); console.log(_str);//y is a fine day var str2 = "today is a fine day"; var _str2 = str2.substring(4,8); console.log(str2);//today is a fine day console.log(_str2);//y is var _str2 = str2.substring(4); console.log(_str2);//y is a fine day var str3 = "today is a fine day"; var _str3 = str3.slice(4,8); console.log(str3);//today is a fine day console.log(_str3);//y is var _str3 = str3.slice(4); console.log(_str3);//y is a fine day var str3 = "today is a fine day"; var _str3 = str3.slice(4,-11); console.log(str3);//today is a fine day console.log(_str3);//y is a var str2 = "today is a fine day"; var _str2 = str2.substring(4,-1); console.log(str2);//today is a fine day console.log(_str2);//toda
String size conversion
- toLowerCase(): converts a string to lowercase
- toUpperCase(): converts a string to uppercase
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Case conversion of string</title> <style> #ipt{ width: 200px; height: 50px; border: 1px solid red; } </style> </head> <body> <div id="outer"> Please enter the verification code: <input type="text" id="ipt"> <button id="con">hj76tr</button> </div> <script> /* * toLowerCase() Convert to lowercase * toUpperCase() Convert to capital letters * */ var oCon = document.getElementById("con"); var oIpt = document.getElementById("ipt"); oIpt.onchange = function () { if (oIpt.value.toLowerCase() === oCon.innerHTML) { oIpt.style.borderColor = "green"; } } </script> </body> </html>
String and array conversion
-
Using the split method of string, you can divide the string into arrays according to the specified delimiter
-
If the parameter is an empty string, it is segmented according to a single character to return an array of the same length as the string
-
If there are no parameters, the string is treated as a value of the returned array
-
Support the second parameter, which represents the maximum length of the array
var str = "hey,of surprise,no,wrong,oh"; var arr = str.split(); var arr2 = str.split(''); var arr3 = str.split(','); var arr4 = str.split(',',3); console.log(str); console.log(arr);//["ouch, ouch, no, wrong, oh"] console.log(arr2);// ["ouch", "ouch", "no", "wrong", "Oh"] console.log(arr3);//["ouch", "ouch", "no", "wrong", "Oh"] console.log(arr4);// ["ouch", "ouch", "no"]
Clear empty strings on both sides
- ES5 adds a trim method to remove leading and trailing empty characters and line terminators from strings
- Commonly used in forms
var str1 = " kajsbd asknj df asf adf \n"; console.log(str1.trim());
Convert string to queue image
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Convert string to object</title> </head> <body> <script> // http://www.baidu.com?username=xiaowang&password=12345&age=18&sex= Female & score = 90 // {username:"xiaowang",password:12345,age:18,sex: "female", score:90} var url = "http://www.baidu. com? Username = Xiaowang & password = 12345 & age = 18 & sex = female & score = 90 "; var obj = {}; var strArr = url.split("?"); // console. log(strArr[1]);// Username = Xiaowang & password = 12345 & age = 18 & sex = female & score = 90 var strArr2 = strArr[1].split("&"); // console.log(strArr2);//["username=xiaowang", "password=12345", "age=18", "sex = female", "score=90"] for (var i = 0; i < strArr2.length; i++) { // strArr2[i].split("=")//["username","xiaowang"] obj[strArr2[i].split("=")[0]] = strArr2[i].split("=")[1]; } console.log(obj);//{username: "xiaowang", password: "12345", age: "18", sex: "female", score: "90"} // Var STR = 'username = Xiaowang & password = 12345 & age = 18 & sex = female & score = 90' function queryString(str) { var obj = {}; var strArr2 = str.split("&"); for (var i = 0; i < strArr2.length; i++) { obj [ strArr2[i].split("=")[0] ] = strArr2[i].split("=")[1]; } return obj; } </script> </body> </html>
Queue image to string
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Convert object to string</title> </head> <body> <script> // It is known that the objects we get are: {username: "xiaowang", password: "12345", age: "18", sex: "female", score: "90"} // The known spliced url address is: http://www.baidu.com // Finally: http://www.baidu.com?username=xiaowang&password=12345&age=18&sex= Female & score = 90 var obj = {username: "xiaowang", password: "12345", age: "18", sex: "female", score: "90"}; var url = "http://www.baidu.com"; // "Username = 12390", "password = 12390", "first target", "password = 12390" var arr = []; for(var i in obj){ var str = i + "=" + obj[i]; // console.log(str);//username=xiaowang arr.push(str); } // console.log(arr); //["username=xiaowang", "password=12345", "age=18", "sex = female", "score=90"] // Second goal: username = Xiaowang & password = 12345 & age = 18 & sex = female & score = 90 var newStr = arr.join("&"); console.log(newStr); var newUrl = url + "?" + newStr; console.log(newUrl); </script> </body> </html>
practice
Given a string such as "abaasdffggghhjjkkgfddsssss3444343", the problem is as follows:
- Length of string
- Take out the characters in the specified position, such as 0, 3, 5, 9, etc
- Find out whether the specified character exists in the above string, such as i, c, b, etc
- Replace the specified characters, such as g with 22,ss with b and other operation methods
- Intercept the string from the specified start position to the end position, for example: get the string of 1-5
- Find out the character with the most occurrences and the number of occurrences in the above string
- Traverse the string, and add the symbol "@" at both ends of the traversed characters to output to the current document page.
Math object
Math object is a built-in object of JavaScript, which provides a series of mathematical constants and mathematical methods. Math objects only provide static properties and methods, so you don't need to instantiate them when using them.
JS object classification
Internal object
- The internal objects in js include Array, Boolean, Date, Function, Global, Math, Number, Object, RegExp, String and various Error class objects, including Error, EvalError, RangeError, ReferenceError, syntax Error and TypeError.
- Among them, Global and Math objects are also called "built-in objects". These two objects are created during the initialization of the script program, and there is no need to instantiate these two objects.
Host object
- The host object is the object provided by the environment in which the JS script is executed. For JS embedded in web pages, its host object is the object provided by the browser, so it is also called browser object, such as the object provided by IE, Firefox and other browsers. The host objects provided by different browsers may be different. Even if the objects provided are the same, their implementation methods are very different! This will bring browser compatibility problems and increase the difficulty of development. There are many browser objects, such as Window and Document, Element, form, image, and so on.
custom object
- As the name suggests, it is the object defined by the developer himself. JS allows the use of custom objects to expand JS applications and functions
Attributes of Math objects
The Math object provides the following read-only mathematical constants.
- Math.E // 2.718281828459045 (natural base infinite non cyclic decimal) LIM (1 + 1 / N) ^ n = e, n → + ∞
- Math.LN2 // 0.6931471805599453 (natural logarithm of 2)
- Math.LN10 // 2.302585092994046 (natural logarithm of 10)
- Math.LOG2E // 1.4426950408889634 (2 is the logarithm of base E)
- Math.LOG10E // 0.4342944819032518
- Math.PI // 3.141592653589793
- Math.SQRT1_2 // 0.7071067811865476
- Math.SQRT2 // 1.4142135623730951
practice:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Math Object properties</title> </head> <body> <h2>Please enter the radius of your home m</h2> <input type="text" id="ipt"> <h2>What is the area of your garden <span id="area"></span>, What is the perimeter of your garden <span id="length"></span></h2> <script> // Get π console.log(Math.PI); //Get natural base console.log(Math.E); //Get the sum of 2 and 1 / 2 square root console.log(Math.SQRT2); console.log(Math.SQRT1_2); // practice var oIpt = document.getElementById("ipt"); var oArea = document.getElementById("area"); var oLength = document.getElementById("length"); oIpt.onchange = function () { oArea.innerHTML = Math.PI * oIpt.value * oIpt.value; oLength.innerHTML = 2 * Math.PI * oIpt.value; } </script> </body> </html>
Method of Math object
Random number exercise
Curvilinear motion of small ball
Basic Edition
Path version
Roll call device
Other exercises Math objects provide the following read-only mathematical constants.
- Math.E // 2.718281828459045 (natural base infinite non cyclic decimal) LIM (1 + 1 / N) ^ n = e, n → + ∞
- Math.LN2 // 0.6931471805599453 (natural logarithm of 2)
- Math.LN10 // 2.302585092994046 (natural logarithm of 10)
- Math.LOG2E // 1.4426950408889634 (2 is the logarithm of base E)
- Math.LOG10E // 0.4342944819032518
- Math.PI // 3.141592653589793
- Math.SQRT1_2 // 0.7071067811865476
- Math.SQRT2 // 1.4142135623730951
practice:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Math Object properties</title> </head> <body> <h2>Please enter the radius of your garden. The unit is m</h2> <input type="text" id="ipt"> <h2>What is the area of your garden <span id="area"></span>, What is the perimeter of your garden <span id="length"></span></h2> <script> // Get π console.log(Math.PI); //Get natural base console.log(Math.E); //Get the sum of 2 and 1 / 2 square root console.log(Math.SQRT2); console.log(Math.SQRT1_2); // practice var oIpt = document.getElementById("ipt"); var oArea = document.getElementById("area"); var oLength = document.getElementById("length"); oIpt.onchange = function () { oArea.innerHTML = Math.PI * oIpt.value * oIpt.value; oLength.innerHTML = 2 * Math.PI * oIpt.value; } </script> </body> </html>
Date object
Get time
Date is used to process date and time
// Get current time var now = new Date(); console.log(now)//Fri Aug 02 2019 14:20:09 GMT+0800 (Irkutsk standard time) console.log(typeof now)//object
Create a time new Date (specify time)
- Pass in a number of milliseconds (the number of milliseconds will be converted into a time c, and then add the time of 8:00 on January 1, 1970)
- When a string format is passed in, 2028-10-2 10[external chain picture transfer fails. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-spcn06xz-1619244581191)( https://github.githubassets.com/images/icons/emoji/10.png )]29
- Pass in multiple parameters to represent month, year, day, hour, minute, second and millisecond respectively
var date1 = new Date(1000 * 60 * 60); var date1 = new Date(1546354578234); console.log(date1); var date2 = new Date("2019-10-01 8:0:0"); var date2 = new Date("2019-10-1");//If you don't write the time, only write the month, year and day, then the time is calculated according to 00 o'clock var date2 = new Date("8:0:0");//Invalid Date if the date is not written, the time is wrong console.log(date2); var date3 = new Date(2019,9,1,8,10,20,300);//When the month is passed or obtained in digital form, the month starts from 0 and 0 represents January var date3 = new Date(2019,16,1,8,10,20,300);//If the time exceeds the minute, it will automatically move forward by one, but it is not recommended to write this console.log(date3);Copy to clipboardErrorCopied
Get time
The time object, whether the current time or the time we set, has a method to obtain the exact month, year, day and other individual times.
- Get year getFullYear
- Get month getMonth
- Get getDate
- Get hours getHours
- Get minutes getMinutes
- Get seconds getSeconds
- Get milliseconds getMilliseconds
- Get week getDay
- Failed to obtain the 8[external chain picture from January 1, 1970. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-cjqderkk-1619244581192)( https://github.githubassets.com/images/icons/emoji/00.png )]00 milliseconds getTime
var now = new Date(); //Get year var nowYear = now.getFullYear(); // var nowYear = now.getYear();// Get only the last two methods before 2000. We don't recommend it console.log(nowYear);//2019 console.log(typeof nowYear);//number //Get month var nowMonth = now.getMonth(); console.log(nowMonth);//7 represents August, and the month starts from 0 //Acquisition day var nowDate = now.getDate(); console.log(nowDate);//2 // Get hours var nowHours = now.getHours(); console.log(nowHours);//24 hours //Get minutes var nowMinutes = now.getMinutes(); console.log(nowMinutes);//42 // Get seconds var nowseconds = now.getSeconds(); console.log(nowseconds)//11 //Get milliseconds var nowMilliseconds = now.getMilliseconds(); console.log(nowMilliseconds); // Get week var nowDay = now.getDay(); console.log(nowDay);//5 //Gets the number of milliseconds from 8:00:00 on January 1, 1970 var nowTime = now.getTime(); console.log(nowTime);
Beijing time practice
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Beijing time practice</title> </head> <body> <div id="time"> <!-- The current time is 14:46:40:018 milliseconds on August 2, 2019--> </div> <script> var oTime = document.getElementById("time"); //Function to add 0 to month, day, hour, minute and second function addZero(n) { return n>10 ? n : "0"+n; } function getNowTime() { var now = new Date(); var y = now.getFullYear(); var m = now.getMonth() + 1; m = addZero(m); var d = now.getDate(); d = addZero(d); var h = now.getHours(); h = addZero(h); var min = now.getMinutes(); min = addZero(min); var s = now.getSeconds(); s = addZero(s); var mili = now.getMilliseconds(); if (mili < 10){ mili = "00" + mili; } else if (mili<100){ mili = "0" + mili; } var nowTime = y + "year" + m + "month" + d + "day" + h + "Time" + min + "branch" + s + "second" + mili + "millisecond" oTime.innerHTML = nowTime; } var timer = setInterval(getNowTime,1); </script> </body> </html>
Set individual time
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Beijing time practice</title> </head> <body> <div id="time"> <!-- The current time is 14:46:40:018 milliseconds on August 2, 2019--> </div> <script> var oTime = document.getElementById("time"); //Function to add 0 to month, day, hour, minute and second function addZero(n) { return n>10 ? n : "0"+n; } function getNowTime() { var now = new Date(); var y = now.getFullYear(); var m = now.getMonth() + 1; m = addZero(m); var d = now.getDate(); d = addZero(d); var h = now.getHours(); h = addZero(h); var min = now.getMinutes(); min = addZero(min); var s = now.getSeconds(); s = addZero(s); var mili = now.getMilliseconds(); if (mili < 10){ mili = "00" + mili; } else if (mili<100){ mili = "0" + mili; } var nowTime = y + "year" + m + "month" + d + "day" + h + "Time" + min + "branch" + s + "second" + mili + "millisecond" oTime.innerHTML = nowTime; } var timer = setInterval(getNowTime,1); </script> </body> </html>
regular expression
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Beijing time practice</title> </head> <body> <div id="time"> <!-- The current time is 14:46:40:018 milliseconds on August 2, 2019--> </div> <script> var oTime = document.getElementById("time"); //Function to add 0 to month, day, hour, minute and second function addZero(n) { return n>10 ? n : "0"+n; } function getNowTime() { var now = new Date(); var y = now.getFullYear(); var m = now.getMonth() + 1; m = addZero(m); var d = now.getDate(); d = addZero(d); var h = now.getHours(); h = addZero(h); var min = now.getMinutes(); min = addZero(min); var s = now.getSeconds(); s = addZero(s); var mili = now.getMilliseconds(); if (mili < 10){ mili = "00" + mili; } else if (mili<100){ mili = "0" + mili; } var nowTime = y + "year" + m + "month" + d + "day" + h + "Time" + min + "branch" + s + "second" + mili + "millisecond" oTime.innerHTML = nowTime; } var timer = setInterval(getNowTime,1); </script> </body> </html>
JavaScript Dom
Bom object
DOM Foundation
JS event
Scripted CSS
Common effects
Tab switching
Method 1
Method 2
Back to the top
Back to top basic
Back to the top animation
Back to the top general animation
sidebar
Tab toggle animation
Rebound against the wall
Method 1
Method 2
Seamless rolling
Seamless rolling continuous plate
Seamless rolling intermittent Edition
Picture rotation
Seamless picture rotation
Lazy loading
Drag
Method 1
Method 2
Method 3
Custom scroll bar
Custom scroll bar slider
Custom scroll bar scale calculation
Automatic height of slider
<script> //Dragging of foundation slider var //Screen height </script>
Slider automatic height synthesis scale
Scroll event
Custom scroll bar scrolling events
DOM advanced
Node operation
Because the relationships of nodes are read-only, DOM provides methods of nodes
Create node
Create text node
Insert node
Replication node
Delete node
Replace node
Element content operation
Reading and inserting HTML strings
Replace HTML string
Read and write text
textcontent
Attribute node
Create attribute node
Read attribute value
Set attribute value
Delete attribute
Custom properties
Document fragment node
Node exchange exercise
DOM advanced
event model
Basic event model: also known as DOM0 event model, it is a simple event model in the early days of browsers
DOM event model:
IE event model:
Netscape event model:
Event flow
Interview questions
Please describe the event flow:
This interview question can be answered in two ways:
1. Text description:
W3C event flow:
Three stages of implementation:
- In the capture phase, the elements are executed successively from the most imprecise element to the most accurate target element
- In the target phase, events on the target node are executed
- In the bubbling phase, events are executed successively from the most accurate target element to the least accurate element.
- W3C provides a new event model. We can specify at which stage the time of the element is executed
2. Graphic description
[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-wnfqaO7e-1619244581195)(C:\Users\juan~er\Desktop(img-wnfqao7e-1619244581195) (C: \ users \ Juan ~ er \ desktop \ 000. PNG)]0.png)]
Here I think it can be explained with the help of words, which makes it clearer
Binding event
Dynamic binding of basic event model
Assign a function to the event attribute, and the function will execute automatically when the event occurs
<body> </body>
Static binding
Event mechanism for binding events (DOM0 events)
Events registered with on + event names are called DOM0 level events. All browsers support this event binding
Registration event
Destruction event
Binding event compatibility
DomContentLoaded event
Event event
Mouse positioning for event events
clientX: locate the x coordinate with the upper left fixed point of the browser window as the origin
offsetx: locate the x-axis coordinate with the upper left corner of the target object of the current event as the origin
pageX: take the top left corner of the document object (i.e. the document window) as the origin and locate the x-axis coordinate (not compatible with IE)
screenX: the top left corner of the computer screen is the origin to locate the x-axis coordinates
<!DOCTYPE html> <html> <head> <meta charset="UtF-8"> <title>event Mouse positioning of events</title> <style> #con{ width:50px; height:50px; background: red; margin:50px 50px; } </style> </head> <body> <div id="con"></div> <script> //Get element var oCon=document.getElementById("con"); //Bind click event oCon.onclick=function(e){ var e=e||window.event; /* //Click div here to print e.clientx and e.clienty of the mouse click position console.log(e.clientX,e.clientY); //clientX The event property returns the horizontal coordinates of the mouse pointer relative to the browser page (or client area) when the event is triggered. //clientY The event attribute returns the vertical coordinate of the mouse pointer to the browser page (client area) when the event is triggered. The client area refers to the current window. */ // console.log(e.offsetX,e.offsetY); // console.log(e.pageX,e.pageY); // console.log(e.screenX,e.screenY); console.log(getEventPage(e)); } //Encapsulation of pageY and pageX function getEventPage(e){ if(e.pageX){ return{ x:e.pageX, Y:e.pageY } }else{ return{ x:document.body.scrollLeft+e.clientX, y:document.body.scrollTop+e.clientY } } } </script> </body> </html>
Introduction to screenX, clientX, pagex and offsetx
concept
1. offsetX and offsetY
- offsetX: the horizontal distance between the mouse click position and the trigger event object
- offsetY: the vertical distance between the mouse click position and the trigger event object
2. clientX and clientY
- clientX: returns the horizontal coordinate of the mouse pointer to the browser page (client area) when the event is triggered. The client area refers to the current window. (the horizontal scrolling distance is not calculated)
- clientY: returns the vertical coordinate of the mouse pointer to the browser page (client area) when the event is triggered. The client area refers to the current window. (the vertical scrolling distance is not calculated)
3. pageX and pageY
-
pageX: returns the position of the mouse pointer relative to the top edge of the document. (calculate the horizontal rolling distance)
-
pageY: returns the position of the mouse pointer relative to the top edge of the document. (calculate the vertical scrolling distance)
4. screenX and screenY
-
screenX: returns the horizontal coordinates of the mouse pointer relative to the screen when the event occurs.
-
Screen: returns the vertical coordinates of the mouse pointer relative to the screen when the event occurs.
graphic
As shown in the figure, assuming that the yellow area in the figure is the mouse click position and the red area is the mouse trigger event object, these attributes can be expressed as:
[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-w49lUHbH-1619244581196)(C:\Users\juan~er\Desktop \ illustration. png)]
Prevent propagation
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Prevent propagation</title> <style> #outer{ width: 100px; height: 100px; background-color:red; position:absolute; } #inner{ width:50px; height: 50px; background-color:yellow; position:absolute; left:50%; margin-left:-25px; top:50%; margin-top:-25px; } </style> </head> <body> <div id="outer"> <div id="inner"> <div id=""></div> </div> </div> <script> /* Prevent propagation: Mainstream browser: e.stopPropagation(); True = cancel IE Only the propagation of the current event can be blocked */ //Get element var oOuter=document.getElementById("outer"); var oInner=document.getElementById("inner"); oInner.onmousedown=function(e){ // e.stopPropagation(); console.log("Press"); } oInner.onmouseup=function(e){ // e.stopPropagation(); console.log("lift"); } oInner.onclick=function(e){ //The above prevent propagation event is effective //This is because the inner click propagates to the outer click //So here we need to propagate the inner click to the block e.stopPropagation(); } oOuter.onclick=function(){ console.log("Click event"); } </script> </body> </html>
Modern browser (mainstream browser): e.stopPropagation();
IE678 browser (lower version IE): e.cancelBubble=true;
Block default events
Default event:
Form submission default
Right click menu
Selected text
In some cases, if these default events are not needed, you need to block the default events
Mainstream: e.preventDefault();
IE:e.returnValue=false;
There is also a simple and crude block default event:
return false;
But it must be written on the last line, or return will exit the function immediately
document.oncontextmenu=function(e){ e.preventDefault(); } //Form submission event //1. Bind submit event to form //2.
Keyboard events
Keyboard events
When the user operates the keyboard, the keyboard event will be triggered
keydown: triggered when a key is pressed on the keyboard. If a key is pressed, the event will be triggered continuously
keyup: triggered when a key is released. Not continuous corresponding state
Keyboard event properties
Keyboard events define many properties
keyCode: the key value of the corresponding key position in the corresponding keyboard
Press enter to submit the form
Event delegation
Event delegation: also known as event proxy or event hosting.
Events are ordinary events that are bound. Delegates are not bound to the target event, but to the parent element or grandparent element.
Principle of event delegation:
Bubbling
Why use event delegation: (advantages)
1.for loop to improve efficiency
2. You can bind events to future elements
<body> <button id="btn">add to</button> <ul> <li>1</li> <li>2</li <li>3</li> <li>4</li> <li>5</li> </ul> <script> var oBtn=document.getElementById("btn"); //Bind click events directly to ul var oUl=document.getElementsByTagName("ul"); oUl.onclick=function(e){ //There is a target attribute in the event object, which represents the target element of the current event console.log(e); } </script> </body>
Select city
JavaScript advanced
Basic in-depth summary
data type
Data type classification
Test data type
typeof: returns a string representation of a data type
Types that can be detected:
-number
-Boolean
-string
-function
-undefined
Not detectable:
- null and object
- general objects and arrays
Judgment array: isArr ()
Congruent judgment:
===: because some types have only one value, they can be judged
-undefined
-null
instanceof/constructor
- cannot judge basic data type
- A instance B: judge whether A is an instance of B (the later prototype chain will be explained in detail)
- use instanceof/constructor to detect arrays and regular arrays
Undefined and Null
Strictly distinguish between variable types and data types
Strictly distinguish between variable types and data types
Variable type:
- basic type (the variable holds a basic value)
- reference type (the variable holds a reference address value)
Data type:
- Basic Type:
-string
-number
-
- object type
Data, variables, memory
data
Memory
variable
The relationship among memory, data and variables
data
Memory
object
practice
On the assignment of reference variables
About data transmission
object
What is an object
Why use objects
How to create objects
Composition of objects
How to access internal data of objects
Object interview questions
//test1 var a={}; var obj1={ n:2 } var obj2={ n:3 } //When setting and obtaining the properties of an object, be sure to convert the key into a string and call toString a[obj1]=4; a[obj2]=5; console.log(a);//My answer: 5 / / error, should be: [object] //Analysis: without carefully analyzing the meaning of printing a here, it is simply understood as outputting the value of A. be sure to pay attention next time!!! console.log(a[obj1]);//5 //test2 /* 2 A reference variable points to the same object. Let one reference variable point to another object, and the other reference variable still points to the original object */ var o3 = { m: 3 } Assignment is the assignment of the value of the variable o1 The address represented is assigned to o2 var o4 = o3 //The address value of o3 is modified, and o4 is still the original value of o3 o3 = { m: 4 } console.log(o4.m, o4 === o3) //3 false //test3 /* 2 Two reference variables point to the same object. The internal data of the object can be modified through one reference variable, and the other reference variable can also be seen */ var o1 = { m: 1 } //Assignment is the assignment of the value of the variable. The address represented by o1 is assigned to o2 var o2 = o1; //Extending the attribute to o2 is actually extending the attribute to the object represented by the o2 address o2.m = 2; console.log(o1.m, o1 === o2) //2 true //test4 var O5={ m:5; }; var o6=o5; //Parameter passing is actually an assignment operation obj=o5 function fn(obj){ //obj is assigned a new value and will not affect o5 and O6 obj={ m:6 }; } fn(o5); console.log(o5.m,o6.m,o6===o5);//5 5 true //test5 var o5 = { m: 5 }; var o6 = o5; function fn(obj) { //O5 O6 obj is the same address obj.m = 6 } fn(o5) console.log(o5.m, o6.m, o6 === o5) //6 6 true //My question: why is 6 here? //Because o5 and o6 here use the same address for data storage, after one of them is changed, the other can also be seen // Two reference variables point to the same object. One reference variable modifies the internal data of the object, and the other reference variable is also visible
function
What is a function
Why use functions
How to define functions
Two roles of function
How to call (execute) a function?
Callback function
IIFE
this in function
What is this
The direction of this
How to judge the direction of this
call apply and bind
call()
apply()
bind()
practice
Interview questions
Handwritten call
Handwritten apply
Handwritten bind
Function advanced
Prototype chain
prototype attribute of function
Each function has a prototype attribute. prototyep is actually a pointer. By default, it points to an Object null Object (i.e. prototype Object) (except for constructor)
The object pointed to by the prototype attribute is called the display prototype
Generally speaking, only the prototype attribute of the constructor is meaningful, because the constructor is used to create the corresponding instantiated object. We will put the public methods of all instantiated objects on the prototype object of the constructor
function Person(){ } cosole.log(Person.prototype); new p1=new Person() console.log(Array.prototype); console.log(String.prototype); console.log(Number.prototype); console.log(Boolean.prototype);
There is a property constructor in the prototype object, which points to the function object
costructor
Constructor properties
Stored on prototype object by default
Constructor that points to the current prototype object
Who can get the constructor (constructor) of an object
function Person(){ } //Only the instantiated object of Person can access test Person.prototype.test=function(){ console.log(test); } console.log(Person.prototype) console.log(Person.prototype.constructor===Person) //Constructor is mainly used to judge who the constructor of an object is console.log(p1.constructor)
Illustration:
Display prototype and implicit prototype
Each function has a prototype, that is, the display prototype. (because only the instantiated object of the constructor can be obtained)
Each instance object has one_ proto_, It can be called implicit prototype.
The value of the implicit prototype of the object is the value of the display prototype of its corresponding constructor.
The search process of prototype chain is through_ proto_ query
Each object has one_ proto_ Property, which can be called an implicit prototype. (because every object may get its properties or methods)
Each function has a prototype, that is, the display prototype. (because only the instantiated object of the constructor can be obtained)
The implicit prototype of the instantiated object points to the display prototype of its constructor
practice
Once we
Array sorting and de duplication
Array.protype.szpxqc=function(){ this.sort(function(){ return a-b; }) console.log(this); var newArr=[]; for(var i=0;this.length;i++){ if(this[i]===this[i+1]){ continue; } newArr.push(this[i]); } } return
Introduction to ECMAScript
JS history
ECMAScript
ECMAScript version
Document address
Keyword extension
let and block level scopes
Function scope
Block level scope
let keyword
let keyword features
const keyword
Function declaration for block level scope
Deconstruction and assignment of variables
What is deconstruction assignment of variables
Deconstruction assignment of array
Deconstruction assignment of object
Deconstruction of assignment
String extension
Template string
Method of adding string
Array extension
Extension operator
What is an extension operator
Other applications
New method of array
New method of Array object
New method on 'Array' prototype
Extension of function
Default values for function parameters
ES5 default parameters
ES6 default parameters
rest parameter
Arrow function
What is an arrow function
Writing method of arrow function
Precautions for arrow function
Extension of Math
Exponential operator
Binary notation
New method of Math
Object extension
Object abbreviation
Property name expression
Object extension operator
Object adding method
Object.is()
Merge method object assign
New data type
Symbol
What is a Symbol
Use of symbols
Symbol represents a unique value
Precautions for Symbol
BigInt
New data structure
Set
What is Set
Properties and methods of Set
Other uses of Set
Map
What is a Map
Properties and methods of Map
iterator
What is iterator
Use of iterator
for...of
For... of and for... in
Generator
What is a Generator
Generator considerations
Generator exercises
async and await
async
await
class
Origin of class
Class inheritance
promise
promise function
Introduction to promise
then and catch methods of promise
Other promise methods
Dynamic import
Object advanced
create object
Public private static privilege
Privilege method:
Directly set the methods and properties of the instantiated object in the constructor
What does the new operator do
- an object was returned
- let the implicit prototype of this object point to the display prototype of the constructor
- this of the constructor points to the instantiated object
Handwritten new
function Student(name,age,sex){ this.name=name; this.age=age; this.sex=sex; } //The constructor itself does not return a value and directly returns the instantiated object //But if you use return? //If function myNew(constr){ //Returns an object var obj={}; //Let the implicit prototype of this object point to the display prototype of the constructor obj._proto_=constr.prototype; //Get the parameters passed to the constructor and get them through arguments var argsArr=Array.from(arguments).slice(1); //Call the constructor and point his this to the instantiated object return obj; }
Encapsulation, inheritance, polymorphism
encapsulation
The purpose of encapsulation is to hide information. Generally speaking, encapsulate data and realize encapsulation.
Encapsulate data
Since js does not define key variables such as private, protected, and public to provide permission access, it can only rely on the scope to implement the encapsulation feature
Encapsulation implementation
Encapsulate the implementation, that is, hide the implementation details and design details. Encapsulation makes the changes inside the object invisible to other objects. The object is responsible for its own behavior. Other objects or users don't care about its internal implementation. Users only need to know how to use it. Encapsulation makes the coupling between objects loose, Objects communicate only through exposed API interfaces (method name, function name).
The most common encapsulation implementation is in JS encapsulation libraries such as jquery, Zepto and Lodash. Users do not care about their internal implementation when using them, as long as they provide the correct functions.
inherit
Inheritance is the ability of subclass objects to use the data and behavior of parent objects.
- Prototype chain inheritance
Routine
- Define a parent type constructor
- Add a method to the prototype of the parent class
- Defines the constructor for the subtype
- Create an object of the parent type and assign it to the prototype of the child type
- Set the constructor property of the subtype prototype to subtype
- Adding methods to subtype prototypes
- Create sub type objects: you can call the methods of the parent class
Key
The prototype of the subtype is an instance object of the parent type
-
Borrowing constructor inheritance
tricks
-
Define a parent type constructor
-
Define subtype constructor
-
Calling parent type constructor in subtype constructor
crux
In the subtype constructor, the generic super() adjusts the parent constructor
- Combined inheritance of prototype chain + borrowing constructor
- Using prototype chain to realize method inheritance of parent type object
- Using super() to borrow the parent type to build a function to initialize the same attribute
polymorphic
JS object polymorphism is inherent: the same operation acts on different objects and can produce different interpretations and execution results. That is, when sending the same message to different objects, these objects will give different feedback according to this information.
function xiaoming(name,classRoom){ console.log(this.name+"go"+this.classRoom+"Teacher class"); } var xiaohua=new xiaoming("xiaohua","123");
Thread mechanism and event mechanism
Process and thread
- Process: an execution of a program, which occupies a unique memory space
- Thread: an independent unit in a process, the basic scheduling unit of cpu, and a complete process of program execution
- Processes and threads
- There is usually at least one running thread in a process: the main thread
- A process can also run multiple threads at the same time. We will say that the program runs in multiple threads
- The data in a process can be directly shared by multiple threads
- Data between multiple processes cannot be shared directly
- Compare single threading with multithreading
Multithreading:
Advantages:
It can effectively improve the utilization of cpu
Disadvantages:
Create multithreading overhead
Inter thread switching overhead
Deadlock and state synchronization
Single thread
Advantages: sequential programming is simple and easy to understand
Disadvantages: low efficiency
- Is JS single threaded or multi-threaded?
js is single threaded
However, using Web Workers in H5 can be multi-threaded
- Is the browser single threaded or multi-threaded?
Some are single threaded
firefox
Old IE
Some are multithreaded
chrom
New IE
Browser kernel
Thoughts caused by browser
js common interview questions
Array quick sort
Array bubble sort
Flattened array
Array de duplication
Calculates the number of occurrences of each value in the string, represented by an object
Find duplicates of two arrays
JQuery
JQuery Basics
produce
JQuery is a JavaScript library that encapsulates native JavaScript functions to get a set of defined
- jQuery has integrated the powerful functions of JavaScript, CSS, DOM and Ajax.
Functions and advantages
- Access and manipulate DOM like CSS
- Modify CSS to control the appearance of the page
- Simplify JavaScript code operations
- Easier event handling
- Various animation effects are easy to use
- Make Ajax technology more perfect
- A large number of plug-ins based on jQuery
- Self extension function plug-in
JQuery advanced
JQuery higher order
Less
What is Less
brief introduction
Dynamic style language belongs to css preprocessor, which extends
address
use
Other css preprocessor languages
Conversion between jquery object and dom object
Premise:
jquery objects cannot use dom objects
Basic grammar of Less
notes
variable
nested rules
operation
Mixed Mixin
Pattern matching and guarding
pattern matching
heavy load
guard
Just understand
String interpolation and escape
Variables can be embedded into strings in a ruby like way through structures like * * @ {name}
If you need to splice with a string, you can use string interpolation
However, the css attribute value cannot be a string
Required in string
function
Logical functions, such as if(), Boolean()
Numeric functions, such as ceil(), pool(), sqrt(), etc
. . .
Reference:[ https://less.bootcss.com/functions/#less-%E5%87%BD%E6%95%B0]
#outer{ }
hsl -- the latest way to set the color
File import
NodeJS
NodeJS overview
NodeJS Templating
Packages and package manager
Node.js core module
Http module
HTTP course
Static resource server
mongoDB
express
Caching mechanism
Browser storage
ajax
Native AJAX
Introduction to AJAX
-
The full name of AJAX is Asynchronous Javascript And XML, which is asynchronous JS and XML.
-
Through AJAX, you can send asynchronous requests to the server in the browser.
-
AJAX is not a new programming language, but a new way to use existing standards.
Introduction to XML
-
XML Extensible Markup Language.
-
XML is designed to transmit and store data.
-
XML is designed to transmit and store data.
For example: I have a student data:
name="Sun WuKong"; age="18"; gender="male";
Expressed in XML:
<stuednt> <name>Sun WuKong</name> <age>18</age> <gender>male</gender> </student>
Now it has been replaced by JSON, which means:
{ "name":"Sun WuKong", "age":"18", "gender":"male" }
How AJAX works
AJAX features
Advantages of AJAX
Disadvantages of AJAX
- No browsing history
- There are cross domain problems
- SEO unfriendly
Use of AJAX
Core object
XMLHttpRequest, all AJAX operations are performed through this object.
Use steps
- Create an XML HttpRequest object
Every object may get its properties or methods)
Each function has a prototype, that is, the display prototype. (because only the instantiated object of the constructor can be obtained)
The implicit prototype of the instantiated object points to the display prototype of its constructor
practice
Once we
Array sorting and de duplication
Array.protype.szpxqc=function(){ this.sort(function(){ return a-b; }) console.log(this); var newArr=[]; for(var i=0;this.length;i++){ if(this[i]===this[i+1]){ continue; } newArr.push(this[i]); } } return
Introduction to ECMAScript
JS history
ECMAScript
ECMAScript version
Document address
Keyword extension
let and block level scopes
Function scope
Block level scope
let keyword
let keyword features
const keyword
Function declaration for block level scope
Deconstruction and assignment of variables
What is deconstruction assignment of variables
Deconstruction assignment of array
Deconstruction assignment of object
Deconstruction of assignment
String extension
Template string
Method of adding string
Array extension
Extension operator
What is an extension operator
Other applications
New method of array
New method of Array object
New method on 'Array' prototype
Extension of function
Default values for function parameters
ES5 default parameters
ES6 default parameters
rest parameter
Arrow function
What is an arrow function
Writing method of arrow function
Precautions for arrow function
Extension of Math
Exponential operator
Binary notation
New method of Math
Object extension
Object abbreviation
Property name expression
Object extension operator
Object adding method
Object.is()
Merge method object assign
New data type
Symbol
What is a Symbol
Use of symbols
Symbol represents a unique value
Precautions for Symbol
BigInt
New data structure
Set
What is Set
Properties and methods of Set
Other uses of Set
Map
What is a Map
Properties and methods of Map
iterator
What is iterator
Use of iterator
for...of
For... of and for... in
Generator
What is a Generator
Generator considerations
Generator exercises
async and await
async
await
class
Origin of class
Class inheritance
promise
promise function
Introduction to promise
then and catch methods of promise
Other promise methods
Dynamic import
Object advanced
create object
Public private static privilege
Privilege method:
Directly set the methods and properties of the instantiated object in the constructor
What does the new operator do
- an object was returned
- let the implicit prototype of this object point to the display prototype of the constructor
- this of the constructor points to the instantiated object
Handwritten new
function Student(name,age,sex){ this.name=name; this.age=age; this.sex=sex; } //The constructor itself does not return a value and directly returns the instantiated object //But if you use return? //If function myNew(constr){ //Returns an object var obj={}; //Let the implicit prototype of this object point to the display prototype of the constructor obj._proto_=constr.prototype; //Get the parameters passed to the constructor and get them through arguments var argsArr=Array.from(arguments).slice(1); //Call the constructor and point his this to the instantiated object return obj; }
Encapsulation, inheritance, polymorphism
encapsulation
The purpose of encapsulation is to hide information. Generally speaking, encapsulate data and realize encapsulation.
Encapsulate data
Since js does not define key variables such as private, protected, and public to provide permission access, it can only rely on the scope to implement the encapsulation feature
Encapsulation implementation
Encapsulate the implementation, that is, hide the implementation details and design details. Encapsulation makes the changes inside the object invisible to other objects. The object is responsible for its own behavior. Other objects or users don't care about its internal implementation. Users only need to know how to use it. Encapsulation makes the coupling between objects loose, Objects communicate only through exposed API interfaces (method name, function name).
The most common encapsulation implementation is in JS encapsulation libraries such as jquery, Zepto and Lodash. Users do not care about their internal implementation when using them, as long as they provide the correct functions.
inherit
Inheritance is the ability of subclass objects to use the data and behavior of parent objects.
- Prototype chain inheritance
Routine
- Define a parent type constructor
- Add a method to the prototype of the parent class
- Defines the constructor for the subtype
- Create an object of the parent type and assign it to the prototype of the child type
- Set the constructor property of the subtype prototype to subtype
- Adding methods to subtype prototypes
- Create sub type objects: you can call the methods of the parent class
Key
The prototype of the subtype is an instance object of the parent type
-
Borrowing constructor inheritance
tricks
-
Define a parent type constructor
-
Define subtype constructor
-
Calling parent type constructor in subtype constructor
crux
In the subtype constructor, the generic super() adjusts the parent constructor
- Combined inheritance of prototype chain + borrowing constructor
- Using prototype chain to realize method inheritance of parent type object
- Using super() to borrow the parent type to build a function to initialize the same attribute
polymorphic
JS object polymorphism is inherent: the same operation acts on different objects and can produce different interpretations and execution results. That is, when sending the same message to different objects, these objects will give different feedback according to this information.
function xiaoming(name,classRoom){ console.log(this.name+"go"+this.classRoom+"Teacher class"); } var xiaohua=new xiaoming("xiaohua","123");
Thread mechanism and event mechanism
Process and thread
- Process: an execution of a program, which occupies a unique memory space
- Thread: an independent unit in a process, the basic scheduling unit of cpu, and a complete process of program execution
[external chain picture transferring... (img-UhO52acH-1619244581197)]
- Processes and threads
- There is usually at least one running thread in a process: the main thread
- A process can also run multiple threads at the same time. We will say that the program runs in multiple threads
- The data in a process can be directly shared by multiple threads
- Data between multiple processes cannot be shared directly
- Compare single threading with multithreading
Multithreading:
Advantages:
It can effectively improve the utilization of cpu
Disadvantages:
Create multithreading overhead
Inter thread switching overhead
Deadlock and state synchronization
Single thread
Advantages: sequential programming is simple and easy to understand
Disadvantages: low efficiency
- Is JS single threaded or multi-threaded?
js is single threaded
However, using Web Workers in H5 can be multi-threaded
- Is the browser single threaded or multi-threaded?
Some are single threaded
firefox
Old IE
Some are multithreaded
chrom
New IE
Browser kernel
Thoughts caused by browser
js common interview questions
Array quick sort
Array bubble sort
Flattened array
Array de duplication
Calculates the number of occurrences of each value in the string, represented by an object
Find duplicates of two arrays
JQuery
JQuery Basics
produce
JQuery is a JavaScript library that encapsulates native JavaScript functions to get a set of defined
[external chain picture transferring... (img-bYnrubp2-1619244581198)]
- jQuery has integrated the powerful functions of JavaScript, CSS, DOM and Ajax.
[external chain picture transferring... (img-yk7V6WqN-1619244581199)]
Functions and advantages
- Access and manipulate DOM like CSS
- Modify CSS to control the appearance of the page
- Simplify JavaScript code operations
- Easier event handling
- Various animation effects are easy to use
- Make Ajax technology more perfect
- A large number of plug-ins based on jQuery
- Self extension function plug-in
JQuery advanced
JQuery higher order
Less
What is Less
brief introduction
Dynamic style language belongs to css preprocessor, which extends
address
use
Other css preprocessor languages
Conversion between jquery object and dom object
Premise:
jquery objects cannot use dom objects
Basic grammar of Less
notes
variable
nested rules
operation
Mixed Mixin
Pattern matching and guarding
pattern matching
heavy load
guard
Just understand
String interpolation and escape
Variables can be embedded into strings in a ruby like way through structures like * * @ {name}
If you need to splice with a string, you can use string interpolation
However, the css attribute value cannot be a string
Required in string
function
Logical functions, such as if(), Boolean()
Numeric functions, such as ceil(), pool(), sqrt(), etc
. . .
Reference:[ https://less.bootcss.com/functions/#less-%E5%87%BD%E6%95%B0]
#outer{ }
hsl -- the latest way to set the color
File import
NodeJS
NodeJS overview
NodeJS Templating
Packages and package manager
Node.js core module
Http module
HTTP course
Static resource server
mongoDB
express
Caching mechanism
Browser storage
ajax
Native AJAX
Introduction to AJAX
-
The full name of AJAX is Asynchronous Javascript And XML, which is asynchronous JS and XML.
-
Through AJAX, you can send asynchronous requests to the server in the browser.
-
AJAX is not a new programming language, but a new way to use existing standards.
Introduction to XML
-
XML Extensible Markup Language.
-
XML is designed to transmit and store data.
-
XML is designed to transmit and store data.
For example: I have a student data:
name="Sun WuKong"; age="18"; gender="male";
Expressed in XML:
<stuednt> <name>Sun WuKong</name> <age>18</age> <gender>male</gender> </student>
Now it has been replaced by JSON, which means:
{ "name":"Sun WuKong", "age":"18", "gender":"male" }
How AJAX works
AJAX features
Advantages of AJAX
Disadvantages of AJAX
- No browsing history
- There are cross domain problems
- SEO unfriendly
Use of AJAX
Core object
XMLHttpRequest, all AJAX operations are performed through this object.
Use steps
- Create an XML HttpRequest object
var xhr=new XMLHttpRequest();