JavaScript
1. General
Ant Design
History of JavaScript
JavaScript is the most popular scripting language
The language styles of Java and JavaScript are very different, just to rub the heat
A qualified back-end person must be proficient in JavaScript
2. Quick start
2.1 importing JavaScript
- Internal label
- External introduction
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <!--External reference--> <!--Note: must appear in pairs, do not change to self closing labels--> <script src="js/action.js"></script> <!--Don't write type Default to text/javascript--> <script type="text/javascript"></script> </head> <body> <!--html Direct use js,But not recommended <script> alert("hello,world!"); </script> --> </body> </html>
alert("hello,world!");
2.2 basic grammar
js has only three variables: let (local variable), var (global variable), const (constant)
js is strictly case sensitive
Necessary debugging instructions for browser
console.log()
// 1. Variable definition var score = 60; // 2. Condition control if (score >= 90 && score <= 100){ alert("A"); }else if (score >= 80 && score < 90){ alert("B"); }else if (score >= 70 && score < 80){ alert("C"); }else if (score >= 60 && score < 70){ alert("D"); } else if (score >= 0 && score < 60){ alert("E"); }else { alert("Incorrect input result!") }
2.3 data type
Values, text, graphics, audio, video
variable
var
let
Naming conventions are the same as in other languages
let is recommended to define local variables
number
js does not distinguish between decimal and integer
123 //integer 123.1 //Floating point number 1.123e3 //Scientific counting method -99 //negative NaN // not a number Infinity //Represents infinity
character string
"abc"
'abc'
Boolean value
true
false
Logical operation
&&
||
!
Comparison operator
= == Equal to (if the type is different and the value is the same, it will also be judged as true) === Absolutely equal to (only when the type and value are the same can it be judged as true)
Note: 1. NaN is not equal to all values, including itself; you can only judge whether it is NaN through isNaN()
2. Floating point number has the problem of lack of precision, and floating point number operation shall be avoided as far as possible
null and undefined
Null null
Undefined undefined
array
var arr = [1,2,3,'hello'];
object
var person = { name: "JayNier", age: 21, tags:['js','ad',1,2] }
'use strict'; / / strict check mode
You need to set the IDEA to support ES6 syntax. You must uninstall the first line of js to prevent some problems caused by the randomness of js
3. Data type
3.1 string
- Normal strings are wrapped with '' and ''
- Note the use of the escape character < / KBD >
\u4e2d unicode character \x41 Ascll character
- Multiline strings are written with `
let msg = `hello world !`;
- Template strings are written in ` and ${}
let name = "Jay"; let age = 20; let msg = `hello, ${name}`; console.log(msg);
- String length
str.length
- String immutable
- toggle case
//This is a square, not an attribute str.toUpperCase(); str.toLowerCase();
- Gets the subscript of the specified character of the string
str.indexOf('t');
- Get substring (header but not footer)
str.substring(1); str.substring(1,3); str.substring[1,3);//An error will be reported after the test
3.2 array
Array can contain any data type
- length
arr.length
Note: you can adjust the size by changing the value of arr.length.
2. indexOf() obtains the index of the following table through the element
3. slice() intercepts a part of the Array and returns a new Array (header but not footer)
4. pop(), push() in and out of the stack
- shift(),unshift()
- sort() sort
- reverse() element inversion
- concat() array splicing to obtain a new array
- join() connector
Print the tiled array, using the specified character link - Multidimensional array
3.3 object
var Object name ={ Attribute name: attribute value, Attribute name: attribute value, Attribute name: attribute value }
{...} represents an object. Key value pairs describe attributes. Multiple attributes are separated by commas, and the last one is not comma
The keys in JavaScript are strings, and the values are of any type
- Object Assignment
person.name = "Jay";
- Using a nonexistent object attribute will not report an error undefined
- Dynamic deletion attribute delete
delete person.name
- Determine whether the attribute is in this object
'age' in person; -> true 'toString' in person; -> true //inherit
- Determine whether the property is the hasOwnProperty owned by the object itself
person.hasOwnProperty('age'); ->true person.hasOwnProperty('toString'); ->false
3.4 Map and Set
New features of ES6
Map
let map = new Map([['Tom',100],['Jack',95],['Lucy',80]]); let sorce = map.get('Tom'); console.log(sorce); map.set('admin',123);//Add element map.delete('admin');//Delete element
Set unordered non repeating set
let set = new Set([1,2,2,2,4,3,4]);//De duplication can be realized set.add(5);//Add element set.delete(1);//Delete element console.log(set.has(4));//Include an element
4. Process control
4.1 condition judgment
if statement
if (score >= 90 && score <= 100){ alert("A"); }else if (score >= 80 && score < 90){ alert("B"); }else if (score >= 70 && score < 80){ alert("C"); }else if (score >= 60 && score < 70){ alert("D"); } else if (score >= 0 && score < 60){ alert("E"); }else { alert("Incorrect input result!") }
switch statement
var d=new Date().getDay(); switch (d) { case 0:x="Today is Sunday"; break; case 1:x="Today is Monday"; break; case 2:x="Today is Tuesday"; break; case 3:x="Today is Wednesday"; break; case 4:x="Today is Thursday"; break; case 5:x="Today is Friday"; break; case 6:x="Today is Saturday"; break; }
4.2 cycle judgment
for loop
for (var i=0; i<5; i++) { x=x + "The number is " + i + "<br>"; }
for in traversal
var person={fname:"Bill",lname:"Gates",age:56}; for (x in person) // x is the index number { txt=txt + person[x]; }
let arr = [123,2142,12414,12341]; for (index in arr){ console.log(arr[index]); }
for of traversal
let arr = [123,2142,12414,12341]; for (x of arr){ console.log(x); }
let map = new Map([['Tom',100],['Jack',95],['Lucy',80]]); for (x of map){ console.log(x); }
let set = new Set([1,2,2,2,4,3,4]); for (x of set){ console.log(x); }
while statement
while (i<5) { x=x + "The number is " + i + "<br>"; i++; }
do { x=x + "The number is " + i + "<br>"; i++; } while (i<5);
5. Function
5.1 defining functions
Definition method I
Absolute value function
function abs(x){ if (x > 0) return x; else return -x; }
If return is not executed, the result undefined will also be returned after the function is executed
Definition mode 2
var abs = function(x){ if (x > 0) return x; else return -x; }
Functions can also be understood as variables
Mode 1 and mode 2 are equivalent
Call function
abs(10); // 10
Parameter problem: JS can pass any number of parameters or not
If there are no parameters, how to avoid them
var abs = function(x){ if (typeof x !== 'number') throw 'Not a Number'; if (x > 0) return x; else return -x; }
arguments
arguments when passing multiple parameters
var abs = function(x){ for (x in arguments) console.log(arguments[x]); }
arguments represents all parameters passed in. It is an array
ES6 new feature: get all parameters except defined parameters rest
var abs = function(a,b,...rest){ console.log(rest); }
5.2 variable scope
local variable
- Variables are declared within functions, and variables are local scopes
- Local variables can only be accessed inside a function
- Because local variables only act within functions, different functions can use variables with the same name
- Local variables are created at the beginning of function execution, and are automatically destroyed after function execution
- If you want to use it outside of a function, you can use closures
global variable
- Variables are defined outside the function, that is, they are global variables
- Global variables have global scope, which can be used by all scripts and functions in the web page
- If a variable is not declared in a function, it is a global variable
Function parameters
Function parameters only work within the function and are local variables
The internal function and external function variables have the same name
The function is searched from "inside" to "outside". Assuming that the function variable with the same name exists outside, the internal function will shield the variables of the external function
Promote the scope of the variable
The JS execution engine automatically promotes the declaration of variables, but does not promote the assignment of variables
Code specification: all variable declarations are placed at the head of the function to facilitate code maintenance
Global variables under HTML
In HTML, the global variable is the window object
let x = "hello"; alet(x); alet(window.x); //The two are equivalent
JS actually has only one global variable window. If any variable (function can also be regarded as a variable) is not found within the scope of the function, it will be searched outward. If it is not found within the scope of the global function, an error RefrenceError will be reported
standard
Since all our global variables will be bound to our window, if different JS files use the same global variables, conflicts will occur
//Create unique global variable let Jay = {}; //Define global variables Jay.a = 10; Jay.b = 100; console.log(Jay.a + Jay.b); Jay.add= function(x,y){ return x + y; }
Put all your code into the unique space name defined by yourself to reduce the problem of global naming conflict
Local scope let
It is recommended to use let to define locally scoped variables
function f(){ for (var i = 0; i < 100; i++) console.log(i);//i out of this scope can still be used console.log(i); }
function f(){ for (let i = 0; i < 100; i++) console.log(i);//i out of this scope can still be used console.log(i); }
Constant const
Before ES6, only variables named with all uppercase letters are constants, which are not recommended to be modified (but can be changed)
const is introduced in ES6
5.3 method
Objects: properties and methods
let Jay = { //attribute name: 'JayNier', birth: 2001, //method age: function(){ let now = new Date().getFullYear(); return now - this.birth; } }; //Method call to add () console.log(Jay.age())
After code splitting
function getAge(){ let now = new Date().getFullYear(); return now - this.birth; } let Jay = { //attribute name: 'JayNier', birth: 2001, //method age: getAge//Here, functions are used as variables }; //Method call to add () console.log(Jay.age()) //getAge() cannot be called directly, otherwise this points to window
apply: controls the direction of this
function getAge(){ let now = new Date().getFullYear(); return now - this.birth; } let Jay = { //attribute name: 'JayNier', birth: 2001, //method age: getAge//Here, functions are used as variables }; //Method call to add () getAge.apply(Jay,[])//this points to the Jay object, and the parameter is null
6. Internal objects
6.1 Date
Basic use
let now = new Date();//Sun Sep 05 2021 22:54:33 GMT+0800 (China standard time) now.getFullYear();//year now.getMonth();//Month 0 ~ 11 now.getDate();//day now.getDay();//week now.getHours();//Time now.getMinutes();//branch now.getSeconds();//second now.getTime();//The time stamp is the number of milliseconds from 1970.1.1 0:00:00 to now console.log(new Date(now.getTime()))//Convert timestamp to time
transformation
let now = new Date(); now.toLocaleString();//"11:00:53 p.m. on September 5, 2021" now.toGMTString();//"Sun, 05 Sep 2021 15:00:53 GMT"
6.2 JSON
JSON and XML
- In the early days, all data transfers used to use XML files!
- JSON is a lightweight data exchange format conceived and designed by Douglas Crockford.
- JSON was first widely used in the development of WEB applications. However, at present, JSON is widely used in JavaScript, Java and Node.js applications. WEB applications developed by PHP and C# mainly use XML.
- The biggest difference between JSON and XML is that XML is a complete markup language, while JSON is not. This makes XML require more effort in program interpretation. The main reason is that the design concept of XML is different from JSON. XML uses the characteristics of markup language to provide excellent scalability (such as XPath), and has the advantages of JSON in data storage, expansion and advanced retrieval. JSON is more suitable for the field of network data transmission because it is smaller than XML and the browser's built-in fast parsing support.
- JSON format replaces XML, which brings great convenience to network transmission, but it is not clear at a glance. Especially when JSON data is very long, people will fall into cumbersome and complex data node search. Developers can find and parse JSON data nodes more conveniently through online JSON formatting tools.
Conversion between JSON string and JS object
Format:
- Both object and Map use {}
- Both array and List use []
- key: value is used for both key value pairs
//create object let user = { name: 'Jay', age: 20, sex: 'boy' } //Object to json string {"name":"Jay","age":20,"sex":"boy"} let jsonUser = JSON.stringify(user); //Convert json string to object let obj = JSON.parse('{"name":"Jay","age":20,"sex":"boy"}');
6.3 Ajax
- AJAX = Asynchronous JavaScript and XML
- AJAX is a technology for creating fast dynamic web pages
- AJAX makes web pages update asynchronously by exchanging a small amount of data with the server in the background. This means that some parts of the web page can be updated without reloading the entire page.
7. Object oriented programming
7.1 object oriented prototype inheritance
let Student ={ name: 'XXX', age: NaN, run: function (x){ console.log(this.name + 'Run away' + x +'kilometre'); } } let Jay = { name: 'JayNier', age: 20 } //Prototype points to Student object = = = inheritance Jay.__proto__ = Student; Jay.run(20);
//Construct a new object, which can be understood as a function function Student(name) { this.name = name; } //Add a new method to Student Student.prototype.say = function (content){ alert(this.name + " say: " + content); } let JayNier = new Student('JayNier'); JayNier.say('Hello!');
7.2 object oriented class inheritance
The class keyword is introduced in ES6
Define class
class Student { //constructor constructor(name){ this.name = name; } hello() { alert('hello'); } } let JayNier = new Student('JayNier'); JayNier.hello();
inherit
class Student { constructor(name){ this.name = name; } hello() { alert('hello!' + this.name); } } class Undergraduate extends Student{ constructor(name,grade){ super(name); this.grade = grade; } gradePrint(){ this.hello(); alert('You passed the exam' + this.grade + 'branch'); } } let JayNier = new Undergraduate('JayNier', 90); JayNier.gradePrint();
Essence: viewing prototype objects
Prototype chain
slightly
8. Operate BOM object
Browser introduction
BOM: Browser Object Models
Browser kernel
window
Window: browser window
navigator
navigator: encapsulates the information of the browser
Browser information can be modified artificially. It is not recommended to use these attributes to judge and write code
screen
Screen: screen information
location
location: URL information of the current page
document
DOM(Document Object Model) defines standard methods for accessing and manipulating HTML documents. He represents an HTML document as a tree structure (number of nodes) with elements, attributes, and text
cookie
History (not recommended)
Browser history
history.back();//back off history.forward();//forward
9. Manipulate DOM objects
HTML DOM tree
A web browser is a DOM tree structure
basic operation
- Update node
- Traversal node
- Delete node
- Add node
To operate a DOM node, you must first obtain the DOM node
9.1 getting DOM nodes
To import the JS file to the bottom of < body >
'use strict'; let h1 = document.getElementsByTagName('h1'); let p1 = document.getElementById('p1'); let p2 = document.getElementsByClassName('p2'); let father = document.getElementById('father'); let children = father.children;
This is native code, and then try to use JQuery
9.2 updating DOM nodes
Except for the elements obtained by id, all the elements obtained by region method are arrays
Text operation
- Modify the text value: p1.innerText = "123";
- HTML text tags can be parsed: P1. InnerHTML = '< strong > 456 < / strong >';
Style operation
p1.style.color = 'blue'; p1.style.fontSize = '50px';
9.3 deleting nodes
Steps to delete a node: first locate the parent node, and then delete yourself through the parent node
<div id = "father"> <h1>Title I</h1> <p id = "p1"> p1</p> <p class = "p2"> p2 </p> </div>
let self = document.getElementById('p1'); let father = p1.parentElement; father.removeChild(p1)
Note: when deleting multiple nodes, children change at any time.
9.4 inserting nodes
After we get a node, we can add an element using innerHTML, but it will overwrite the original content information
<p id = 'title'> Hello, world!</p> <div id = "father"> <h1>Title I</h1> <p id = "p1"> p1</p> <p class = "p2"> p2 </p> </div>
Change the node position to realize insertion
'use strict'; let father = document.getElementById("father"); let title = document.getElementById("title") father.appendChild(title);
Create a new common node and insert it
let father = document.getElementById("father"); let x = document.createElement('p');//Create a p label x.id = "new"; x.innerText = "I'm baby!"; father.appendChild(x);
Create a new label node and insert it
let father = document.getElementById("father"); let myScript = document.createElement("script"); myScript.setAttribute("type","text/javascript"); father.appendChild(myScript);
Insert style
let myStyle = document.createElement('style');//Create style labels myStyle.setAttribute('type', 'text/css'); myStyle.innerHTML = `body{//new style background-color: ; }`; document.getElementsByTagName('head')[0].appendChild(myStyle);//get is an array
Insert at the front
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <p id = 'title'> Hello, world!</p> <div id = "father"> <h1>Title I</h1> <p id = "p1"> p1</p> <p class = "p2"> p2 </p> </div> <script src="js/action.js"></script> </body> </html>
let parentNode = document.getElementById('father'); let newNode = document.getElementById('title'); let referenceNode = document.getElementsByClassName('p2')[0]; let insertedNode = parentNode.insertBefore(newNode, referenceNode);
10. Form operation
Get form information
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id = "form"> <form action="" method="post"> <p> <label> <span>user name:</span> <input type="text" id = "username"> </label> </p> <p> <label> <span>Gender:</span> <input type = "radio" name = "sex" value="man"> male <input type = "radio" name = "sex" value="woman"> female </label> </p> <button id = "submit" onclick="getInformation()">Submit</button> </form> </div> <script src="js/action.js"></script> </body> </html>
'use strict'; function getInformation(){ let sex, username; //Get user name username = document.getElementById("username").value; //Gets the selected value of sex for (let i = 0; i < document.getElementsByName("sex").length; i++) if (document.getElementsByName("sex")[i]) sex = document.getElementsByName("sex")[i].value; alert(username); alert(sex); }
Form encryption
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.bootcdn.net/ajax/libs/blueimp-md5/2.18.0/js/md5.js"></script> <script src="https://cdn.bootcdn.net/ajax/libs/blueimp-md5/2.18.0/js/md5.min.js"></script> </head> <body> <div id = "form"> <form action="#" method="post" onsubmit="return check()"> <p> <label> <span>user name:</span> <input type="text" id = "username" name="username"> </label> </p> <p> <label> <span>password:</span> <input type = "password" id = "password"> </label> </p> <p> <label> <input type = "hidden" id = "password_MD5" name="password" hidden> </label> </p> <button type = "submit">Submit</button> </form> </div> <script src="js/action.js"></script> </body> </html>
'use strict'; function check(){ let username, password, password_MD5; username = document.getElementById("username").value; password_MD5 = document.getElementById("password_MD5");//You can't assign values directly. If you assign values here, then password_MD5 is always empty and cannot be reset password = document.getElementById("password").value; password_MD5.value = md5(password); if (username.toString() === "" || password.toString() === ""){//Password cannot be used here_ MD5 judges that there is a value for empty after encryption d41d8cd98f00b204e980998ecf8427e alert("Please enter your user name and password"); return false; } return true; }
11. jQuery
BootCDN
Help documentation
There are a lot of JavaScript functions in the jQuery library
Formula: $(selector). Action (function body)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src = "lib/jquery-3.6.0.js"></script> </head> <body> <p id = 'test'>Point me</p> <script> $('#test').click(function (){ alert("hello, world!"); }) </script> </body> </html>
Selector is written in the same way as css selector
selector
Suggested view Help documentation
Three basic selectors
$('#id').click(); $('p').click(); $('.class').click();
event
Mouse events, keyboard events, other events
The code that runs when the DOM is loaded can be written as follows:
$(document).ready(function(){ // Write your code here });
Abbreviation for $(document).ready()
$(function($) { // You can continue to use $as an alias here });
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src = "lib/jquery-3.6.0.js"></script> </head> <style> #test{ width: 500px; height: 500px; border: 1px solid red; } </style> <body> <h1>Please move the mouse within the box</h1> <p id = 'location'></p> <div id = 'test'> </div> <script> //Code that runs when DOM loading is complete $(function (){ $('#test').mousemove(function (e){ $('#location').text("x: " + e.pageX + " y: " + e.pageY); }) }) </script> </body> </html>
Manipulating DOM elements
Node text operation
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src = "lib/jquery-3.6.0.js"></script> </head> <body> <div id = "father"> <h1>Title I</h1> <p id = "p1"> p1</p> <p class = "p2"> p2 </p> </div> <script> $('p[id = p1]').text();//Get value $('p[id = p1]').text("Modify value");//Modify value $('p[id = p1]').html();//Get value $('p[id = p1]').html("Modify value");//Modify value </script> </body> </html>
css operation
$('p[id = p1]').css({color:'red'});//Key value pair
Show and hide
$('p[id = p1]').show(); $('p[id = p1]').hide();
antic
- How to consolidate JS (see jQuery source code and game source code)
- How to consolidate HTML and CSS (pick websites)