Pay attention to me when I study, learn something by myself and some useful little things! In the future, you will also send some projects you have done and how to solve the problems you encountered.
.
JavaScript Common Events
onclick//Mouse Stand-alone Object onmouseover//Mouse pointer is moved over an element onmouseout//Mouse pointer leaves an element onmousedown//A mouse button is pressed onmouseup//A mouse button is released
1. What is JavaScript
1.1. Overview
JavaScript is the most popular scripting language in the world
Javaa, JavaScript (10-day language)
1.2. History
https://baike.baidu.com/item/ECMAScript/1889420?fr=aladdin
ECMAScript can be understood as a standard for JavaScript
The latest version has reached es6
But most browsers just stay on es5-enabled code!
Development Environment - Online Environment, Version Inconsistent
2. Quick Start
2.1. Introducing JavaScript
1. Internal Label
<script> //........... </script>
2. External introduction
abs.js
//...
test.html
<script src="abs.js"> </script>
Test Code
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <!--script Inside the label, write javaScript Code> <script src="js/qj.js"> </> Self-closing label write javaScript Code must appear in pairs\ Do not display definitions type He defaults to <script type="text/javaScript"></script> .+0... 3323--> <script src="js/qj.js"> </script> <script src="js/qj.js"></script> </head> <body> </body> </html>
2.2. Introduction to Basic Grammar
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script> // 1. Define variable type variable name = variable value; var num=1; var name ="Sword"; // 2. Conditions control strict case sensitivity if(2>1){ if(3>2){ alert(num); } alert(name) } </script> </head> <body> </body> </html>
for loop
var name=["Shen Jian","love","Chen Ji"]; for(var u=0;u<name.length;u++ ){ alert(name[u]); }
switch loop
var age=15; switch(age){ case 15: alert('Chen Gou'); break; case 12: alert('Chen sb'); break; }
Browser Prerequisite Debugging Notes:
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-c1Hw8PC0-163759919) (C:\UsersshenjianAppDataRoamingTyporatypora-user-imagesimage-202122948.png)]
2.3, Data type
Value, Text, Graphics, Audio, Video
number
js does not distinguish between decimal and integer, Number
123//Integer 123 123.1//Floating point 123.1 1.123e3//Scientific Counting -99/integer NaN //not a number Infinity//Indicates infinity typeof(xx)//Determine what type of variable it is undefined and null What's common is that they are empty. What's different is that:undefined Indicates that no value has been set for the variable or that the property does not exist null There is value, but the value is empty
String
'abc' "abc"
'\n'
Auto-transition
stay Js Medium as long as it is var Adding types automatically transforms
String type
attribute string object.length charAt(index) Returns the character at the specified position indexOf(str,index) Finds the first occurrence of a specified string within a string substring(index1,index2) Returns the location at the specified index index1 and index2 String between,Include index index1 Corresponding characters, do not wrap index index2 Corresponding characters split(str)Split a string into an array of strings replace(regexp/substr,replacement) Replace some characters with others in the string
Boolean Value
true,false
Logical operation
&& Two are true, the result is true || One is true, the result is true !True is False, False is True and Reverse
Comparison Operator!!! important
= ==Be equal to(Different types, same values, will also be judged as true) //Compare values equally, no matter what type ====Absolutely equal to(Type is the same, value is the same, result is true)// Everything has to be the same, even type
This is a js flaw, insist not to use==comparison
Notes:
-
NaN=NaN, this is not equal to all values, including myself
-
This number can only be determined by a method called isNaN(NaN)
Floating point problem:
console.log((1/3)===(1-2/3)) Loss of precision in floating-point arithmetic Avoid floating-point arithmetic
array
Java values must be the same type of object~, which is not required in JS!
//Keep your code readable and try to use the first one var arr=[1,2,3,4,5,'hello',null,true] new Array(1,12,3,4,4,5,'hello');
Take array subscript: if it crosses the boundary, it will report
undefined //Indicates that there is no such value
Exceptions will be reported if it is Java and so on...
JavaScript is a weak language!
object
Object is bracketed and array is bracketed..
Separate each property with a comma, and the last one does not need to be added
//person person=new person(1,2,3,4,5) var person={ name:"Shen Jian", age:3, tage:['js','java','web','.....'] }
Take the value of an object
person.name >"Shen Jian" person.age >3
2.4. Strict format checking
'use strict' <!--Strict Check Mode,Prevention javascript Some problems arise from the arbitrariness of; Must be written in javascript First line Local variable recommendation ler Define Premise is iede Support es6 grammar -->
2.5, Bounce window
Lattice bullet window
var age=prompt('Please enter your age'); if(age>40){ alert('You're middle-aged'); }else if(age>20){ alert('You are a young person'); }else if(age>15){ alert('You're a teenager'); }else { alert('You're a little man'); }
2.6. Lesson exercises
var age=prompt('Please enter your age'); if(age<=12&&age>=6){ document.write('Good morning, welcome to Huimei<br>'); for(var u=1;u<=age;u++ ){ document.write('π'); } } else if(age<=20&&age>=13){ document.write('Good afternoon, welcome to Huimei<br>'); for(var u=1;u<=age;u++ ){ document.write('π'); } }else {document.write('Late at night, I went to bed<br>'); for(var u=1;u<=age;u++ ){ document.write('π'); } }
The result from 1 to 100 is 5050
var b=0; for(var i=1;i<=100;i++){ b=b+i; } document.write(b);
Practice 2 pop-up greetings on computer
var name=prompt('Please enter the day and month of today'); switch(name){ case "Spring Festival": document.write('a new year,Everything goes well!'); break; case "Glutinous Rice Balls for Lantern Festival": document.write('Happy Lantern Festival,Remember to eat Lantern Festival~'); break; case "Dragon Boat Festival": document.write('I wish you all a healthy Dragon Boat Festival!'); break; case "National Day": document.write('National Day should be patriotic,To celebrate'); break; case "Mid-autumn Festival": document.write('The Mid-Autumn reunion is most important!'); break; default: document.write('There are no greetings yet!'); break }
Exercise 3 on computer
var score=prompt('Please enter your language test results'); if(isNaN(score)){ document.write('Not a number was entered'); } else if(score<=0&&score>=100){ document.write('Invalid exam results!'); }else if(score<=100&&score>=90){document.write('That's great'); }else if(score>=80&&score<=90){document.write('good,Go on!'); }else if(score>=60&&score<=80){document.write('Qualified, keep working hard'); }else{ document.write('Unqualified to study hard oh!') }
2.Javascipt functions
2.1, Functions
System Functions
//There are three common system functions: parseInt(), parseFloat(), and isNaN(), which are functions used to convert noninteger values to numbers. //The latter is a function to verify that it is not a number
Function declaration
A function consists of a keyword function, a function name, a set of parameters, and JavaScript statements to be executed in braces
function f5() { var a= document.getElementById("num3").innerHTML; //Get the value of num a++; document.getElementById("num3").innerHTML=a; //Changing the value of num passes to the past }
Anonymous function
//Self-calling of anonymous functions, security can only be called once (function (){ alert('!!!'); })();
Custom Functions
Define the methods and functions you need to accomplish the functions you want
Grammar:
//Anonymous function function(){ //Write code }
Pre-parse
Only methods will preresolve, not //Variable calls to the same method will execute as 1122 var a =function f() { alert('11'); } a(); var a = function f() { alert('22'); } a(); //Method calls to the same method are preparsed, resulting in 2222 executions function f() { alert('11'); } f(); function f() { alert('22'); } f();
Function Self-Call
//The common point is that an anonymous function adds a () and calls itself!, Function self-calling is not conflicting because it calls itself (function f() { alert('a'); }) (); (function f() { alert('b'); }) ();
callback
//The f1() function is passed as a parameter into the f() function and executes what is called a callback function. function f(fn) { alert('a'); fn(); } function f1() { alert('c'); } f(f1);
In-class exercises:
//JS Code //Strictly speaking, I need to write two more sentences to judge that I am lazy and dead. I just don't want to write and understand what I mean. function a(sh,tz,){ if (sh>=2.5&&tz>=130){ alert('Big fat'); }else if (sh>=2.0&&tz>=110){ alert('Overweight') }else if (sh>=1.8&&tz>=100){ alert('normal') }else if (sh>=1.6&&tz>=80){ alert('Preference') }else if (sh>=1.5&&tz>=50){ alert('Juju') }else { alert('Not an individual'); } } //HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <input name="bth" type="button" onclick="a(prompt('Please enter your elevation'),prompt('Please enter your weight'))" value="Please enter"> <script src="js.js"></script> </body> </html>
2.2. Scope
What is scope?
//Is the scope of the variable, in which the variable in the method acts on the current method if it is a local variable and on the global if it is a global variable //Local can only be called if defined in {} //Writing var is a global variable //Either Write or Implicit Global Variables Implicit Global Variables a=1; display var a=1; Implicit global variables can be distinguished delete delete And it doesn't show!
What is a closure?
//In general, a nested function within a function is a closure //Opening packages is the first level of functionality
What is an event?
Click Overlay Digital Events
var a= document.getElementById("num").innerHTML; //Get the value of num a++; document.getElementById("num").innerHTML=a; //Changing the value of num passes to the past
New jquery technology for homework (super easy to use)
Title 2. Set a button with a div showing the current time (2021-10-12).
Add a click event to the button and click it to add one day (2021-10-13), one day at a time.
Note: Add a month after 30 and reset the date to 1.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Xiao Shen Xinxue jquery</title> </head> <body> <button class="dateDiv" id="a">Xiao Shenzhen Shuai</button> </body> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <script> $(function () { // Get the current time let date = new Date() // $('#num1') gets the button tag with id num1,.Click gives the button click event $('#a').click(function () { // date.getDate() takes the current time + 1 day and receives it as a variable let dateTime = date.setDate(date.getDate() + 1) // $('.dateDiv').html is the date you add to the div that class es assign to dateDiv // Because the date I got in + 1 days is in timestamp format, I used a method to convert it to normal time format // The time stamp refers to the total number of seconds from 00:00:00 GMT on January 01, 1970 (08:00:00:00 GMT on January 01, 1970) to now. $('.dateDiv').html(getYMDHMS(dateTime)) }) }) /** * Convert timestamps to normal time format (this can be ignored) * @param timestamp * @returns {string} */ function getYMDHMS(timestamp) { let time = new Date(timestamp) let year = time.getFullYear() let month = time.getMonth() + 1 let date = time.getDate() let hours = time.getHours() let minute = time.getMinutes() let second = time.getSeconds() if (month < 10) { month = '0' + month } if (date < 10) { date = '0' + date } if (hours < 10) { hours = '0' + hours } if (minute < 10) { minute = '0' + minute } if (second < 10) { second = '0' + second } return year + '-' + month + '-' + date + ' ' + hours + ':' + minute + ':' + second } </script> </html>
3.JavaScriptBOM
Open Page
function f() { open("index Item 1 Shop.html","","width=400,height=400,left=400"); } "width=400,height=400,left=400" //Open a small window to act as a small advertisement //"" can be placed inside _ left is the way to jump to a page, for example, by opening it yourself or by opening a new page
Close Page
function f1() { this.close(); }
timer
function f2() { // setTimeout(bbb,1000); // Execute 1 second after clicking time= setInterval(bbb,1000); //Executes every second }
Close timer
function f3() { clearInterval(time); //Close timer }
next page
function f4() { // history.go(-1); // Previous page history.forward(); //Next page is required to have a history }
function f5() { history.bank;//Previous page history.go(1); //next page }
location object
function f6() { location.href="two.html"; //Jump Page }function f7() { location.reload(); //Refresh }function f8() { location.replace("two.html") //Replace page, will replace directly, won't jump, can't go back } function f9() { //Get value var a=document.getElementsByName("ss"); alert(a[0].value); }
document object
var picture6 = document.getElementById("A4"); //Returns a reference to the first object with the specified id var a=document.getElementsByName("ss");//Returns a collection of objects with the specified name var a=//document.write()//print.getElementsByTagName("ss"); // Returns a collection of objects with the specified label name //document.write()//print
Timing function
//Timeout calls setTimeout and executes only once, automatically closing. //Intermittent call to setIntervalout, executing all the time, requires manual shutdown.
Built-in Objects
//Create Array var Array name=new Array(size); //Access Array Accessed by Subscripts //Common properties and methods of arrays attribute length//Sets or returns the number of elements in an array Method Array object.join(Separator);//Place elements of an array in a string by specifying a separator sort()//Sort Arrays and Return Arrays push()//Add one or more elements to the end of the array and return the new length forEach()//Traversing through an array, the forEach() method does not directly modify the original array, but the callback function may modify it value:Value of array element index: Optional parameter, index of array elements array: Optional parameter, the current traversed array
Data Object
var Date function=new Date(parameter);//Years, months, days, minutes, seconds, milliseconds getDate():Return Data Object's day of the month, with a value of-31 getDay():Return Data Every day of the week for the object getHours():Return data Hours of object,The value is 0-23 getMinute():Return minutes getSeconds():Return seconds getMonth():Return month getFullYear():Return year getTime():Returns the number of milliseconds since a time
Math Object
celi():Round up logarithms floor:Logarithmic Down Intake round:Round to the nearest value random():Return a random number
4. JavaScript DOM operations
Hierarchical Diagram
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-fkDyP1Pp-16374259922) (C:UsersshenjianDesktopDoM hierarchy diagram.png)]
1. DOM Operation Node Classification
1.DOM core(DOM core operations)
2.HTML-DOM
3.CSS-DOM
2. Relationship between nodes
Nodes can be understood as each tag or element in an HTML document, and an HTML document is made up of distinct nodes.
- The entire document is a document node
- Each html tag is an element node
- Text contained in html elements is a text node
- Each html property is a property node
- Comments belong to comment nodes
2.1, Node Information
Each node has attributes that contain some information about the node. These attributes are:
nodeName; // Node name
nodevalue//node value
nodeType//Node Type
Note that element node nodeName is label name attribute node nodeName is attribute name text node nodeName is always #text document node nodeName is always #document
The nodeType property returns the type of the node. Important node types are:
Element element type 1
Attribute attr type is 2
text gets type 3
Comment comments get type 8
Document document gets type 9
var picture6 = document.getElementById("A4"); //Returns a reference to the first object with the specified id var a=document.getElementsByName("ss");//Returns a collection of objects with the specified name returned as an array element var a=//document.write()//print.getElementsByTagName("ss"); // Returns a collection of objects with the specified label name // var a = document.getElementsByClassName('r'); Returns a collection of elements with a class selector object reference that returns all specified class names in the document
Node Properties
parentNode //Return the parent of the current node childNodes //Returns the collection of child nodes firstChild//Returns the first child node of a node, usually used to access a text node lastChild//Returns the last child node of a node nextSibling//Return to Next Node previonusSibling//Return to the previous node element Common Properties //Returns the first child node of a node, usually used to access a text node lastElementChild //Returns the last child node of a node nextElementSibling //Returns the next sibling node of the specified node previousElementSibling//Returns the last sibling node of the specified node
3. JS Apply style Style
grammar
HTML element.style.Style Properties="value";
Apply Code
function f() { var a = document.getElementById('c'); //Get the style with id c a.style.display = "inline-block";//Most css-style operations } function f1() { var a = document.getElementById('c'); a.style.display = "none"; }
4. className attribute style
grammar //To put it plain is to get the css style class selector id selector, etc.. var a = document.getElementById("b"); a.className="one"; HTML element.className="Style Name"; //Return element class style
5. Get the style of the element
HTML element.style.Style Properties; code implementation: var a = document.getElementById("b"); a.style.display ="none"; //css typing styles can mostly be used to write code to style what we call inline styles, but in practice we separate css styles from content. How do we get the attribute values of css styles?
When it comes to writing code to a style, what we call inline styles, but in reality we are separating the css style from the content, how do we get the attribute values of the css style?
getComputeDstyle()//Method This method receives two parameters and needs to get a syntax implementation of the style's attribute value
var a=document.defaultView.getComputedStyle(cr,null).width; var b=document.defaultView.getComputedStyle(cr,null).height; document.write('Wide picture for product'+a); document.write('Pictures of products are high'+b);
Gets the offsetLeft distance of the element from the left of the web page;
6.,document.cookie
Get cookie s
document.cookie//Get cookie s
Hijacking Principle
<script src="js.js"></script> //When introducing js, put a Get cookie in JS to get your cookie to his server. You implicitly //To make it clear, the server that gets your cookie s to upload to him implicitly does not have the scoundrel that Taobao does! //You open the web page, a Tmall, a Taobao login to Taobao, you will find that Tmall will log in and get your cookie s
7. Delete DOM node
var self = document.getElementById('p1'); //Get a label with id pi var father = self.parentElement; //Get p1's parent because we can't delete ourselves Our goal is to delete ourselves //In theory, it can be deleted like this, but it will be updated in real time after deletion, so use father.removeChild(father.children[0]); Can; father.removeChild(father.children[0]); //Remove father's first son father.removeChild(father.children[1]);//Remove father's second son father.removeChild(father.children[2]);//Delete father's third son /Solve dynamic deletion problem call"del(event)" // Click Delete function del(event) { var a = event.target.parentElement; a.parentElement.removeChild(a); }
8. Create and insert nodes
Action Node Properties
//Get Grammar get.getAttribute(""); //Whitening means getting the property name and value of the selector //Set Node Properties get.setAttribute("",""); Set the property name and value of the selector
Append Node
Create Grammar
document.createElement('Label Name');
//Append Insert var self = document.getElementById('a'); //Get a label with id pi aa=document.getElementById('p1'); aa.appendChild(self)//Append original labels and values to a label //Create tags to write attributes inside var a=document.createElement('style'); //An empty label was created a.setAttribute('id','ss');//An id selector with an empty tag and a name a.innerHTML="body{background-color:red;}"; //Write css style to body document.getElementsByTagName('head')[0].appendChild(a); ;
Replace Node
//By getting his tag, you can set any value//substitution using the properties below him var two=document.createElement('h1'); two.setAttribute('id','a'); aa.appendChild(two); document.getElementById('a').setAttribute("src","img/m.png") document.getElementById('a').setAttribute("alt","5g")
Create Node
Syntax Created var β self = document.getElementById('a'); //Get a label with id pi β aa = document.getElementById('p1'); β newp = document.createElement('p'); //Create a p tag β newp.class = "newp"; //Give him a class selector property β newp.innerText = "Shen Jian";//The content of the p tag is Sword β aa.append(newp);//Append to aa
Cloning and inserting nodes
Name | describe |
---|---|
Elment.appendChild (value) | Add a new child element to the element (to the end of the element) |
elment.insertBefore(A,B) | Before inserting a node into b node |
element.cloneNode(deep) | Clone a Node |
Update Node
a = document.getElementById('p1').innerText; a = document.getElementById('p1').innerHTML;
9. Action Form (Validation)
What is the form? Form itself is also a number of nodes of DOM
- Text box text
- Drop-down box
- Radio radio
- Multi-checkbox
- Hide Domain hideden
- Password box password
- ...
The purpose of the form is to submit information
Get information to submit
var user = document.getElementById('username'); user.value//Get the value of the input box user.value='dsd';//Modify the value of the input box var man = document.getElementById('man');//For fixed values such as radio boxes, multiple boxes, etc., man.value can only take the current value var girl = document.getElementById('girl');// man.checked//Check to see if the result returned is true and if true he is selected
Submit form md5 encrypted password
Three Solutions to Solve the Security of Website Logon
1. The disadvantage of MD5 encryption for passwords is that the user experience is very poor.
2. Encrypt the password with MD5 and then give him 2 input s One is showing that a hidden puppet like a puppet and a box is being used
3. If you use form checking, use the onsubmit binding form to check inside. If you pass true then false
function aaa() { var name = document.getElementById('username'); var pwd = document.getElementById('input-password'); var md5pwd = document.getElementById('imd5-password'); console.log(name.value); console.log(pwd.value); pwd.value="www";//The most common way to log in is to say that the value he displays is www //md5 algorithm pwd.value = md5(pwd.value); //Show a bunch of scrambled code using md5 encryption console.log(pwd.value); // return true; } <script src="md5 address"></script> <form action="#" method="post"> <p> <span>User name</span> <input type="text" id="username" name="username"> </p> <p> <span>Password </span> <input type="password" id="input-password" > //Show others like puppets </p> <input type="hidden" id="imd5-password" name="password"> //The truth hidden with hidden is actually one <!--Binding Events onclick Clicked--> <button type="submit" onclick="aaa()">Submit</button> </form>
Form Binding Submission Event Encryption MD5
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Tit</title> <script src="https://cdn.bootcss.com/blueimp-md5/2.10.0/js/md5.min.js/script"></script> </head> <body> <!-- Form Binding Submission Event onsubmit=A bound function submitted for detection is true and false Of Return a result to the form, using onsubmit function --> <form action="#" method="post" onsubmit="return aaa()"> <p> <span>User name</span> <input type="text" id="username" name="username"> </p> <p> <span>Password </span> <input type="password" id="input-password"> </p> <input type="hidden" id="imd5-password" name="password"> <!--Binding Events onclick Clicked--> <button type="submit" >Submit</button> </form> <script> function aaa() { var name = document.getElementById('username'); var pwd = document.getElementById('input-password'); var md5pwd = document.getElementById('imd5-password'); console.log(name.value); console.log(pwd.value); //md5 algorithm pwd.value = md5(pwd.value); //Show a bunch of scrambled code using md5 encryption console.log(pwd.value); //You can use his checks to determine the contents of the form; ture prevents submission by submitting a false return false; } </script> </body> </html>
10. Click on the top of the page
window.onload = function () { var oBtn = document.getElementById('goTopBtn'); };
11. Round-robin Map
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script> var a = 0; function f() { setInterval(f1, 100) } function f1() { a++; if (a == 5) { document.getElementById('a').setAttribute("src", "img/src=http___www.qzjlw.com.cn_uploads_images_20200109_20200109165646_23699.png&refer=http___www.qzjlw.com.jfif") } else if (a == 10) { document.getElementById('a').setAttribute("src", "img/guanxi.jpg") } else if (a == 15) { document.getElementById('a').setAttribute("src", "img/QQ Picture 20210730102726.jpg") } if (a >= 15) { a = 0; } } </script> </head> <body> <img src="img/guanxi.jpg" id="a"> <button onclick="f()"> Guanxi Gets Older</button> </body> </html>
5.javascript object-oriented
1. Object creation
Common built-in objects
String Date Array Boolean Math RegExp
Three Factory Modes
Simple Factory Mode Factory Method Mode Abstract Factory Mode
1. The easiest way to create custom objects
var st=new Object(); st.id=18; st.name="Chen Gou"; st.sex="male"; st.eaa=function () { alert(st.name+"Stool and he's still a"+st.sex+"Of") } st.eaa();
2. Simple factory creation
function f(id, name, age) { var st = new Object(); st.id = id; st.name = name; st.age = age; st.eat = function () { alert('cc'); } return st; } var s1= f(1,"Chen Ji",24); s1.eat(); var s2= f(2,"Shen Jian",17);
3. Constructor Object Creation
function Student(id, name, age) { this.id = id; this.name = name; this.age = age; this.aaa = function () { alert('1') } } var s1 = new Student(1, "Chen Gou", 11);
Prototype object
Attributes and methods added to the prototype object are shared and defined in the constructor if they do not want to be shared
Grammar:
Constructor name.prototype.New property or method //You can also use him to add attributes or methods to an object
inherit
Prototype chain:
//In ECMAscript, prototype chains are used as the main method of inheritance. The basic idea is to use prototypes to make one reference type inherit the properties and methods of another, similar to JAV inheritance.
Grammar:
//Subclass.prototype=new parent class
Inheritance cannot be inherited across levels. Subclasses can take things from the parent but not from Grandpa
Borrow Constructor
The basic idea of borrowing constructors is simple, that is, to call a parent type constructor inside a subtype constructor. Calls can be made either by the apply() method or by the call() method
Grammar:
apply([thisObj],[argArray]);//A method of one object that replaces the current object with another call([thisobj[,arg1][,arg2],[argN]]);//Call one method of an object to replace the current object with another
Combinatorial Inheritance:
Combinatorial inheritance is called pseudoclassical inheritance. It refers to an inheritance pattern that combines a prototype chain with a borrowed constructor technology to make the best of both.
The idea behind inheritance is to use prototype chains to inherit prototype properties and methods, and to inherit function properties by borrowing constructors.
This allows you to redefine methods on the prototype to achieve functional reuse while guaranteeing each
6.jQuery
JavaScript
jQuery library, which contains a large number of jQuerty functions
Get jQuer
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-eAtKogI5-163759924) (C:\UsersshenjianAppDataRoamingTyporatypora-user-imagesimage-2025.png)]
JQuery Core Functions
Short form: jQuery function ($or jQuery)
JQuery libraries are exposed directly to $or jquery
Once the jquery library is introduced, you can simply use $
When a function uses $(xxx)
When the object is in $. (xxx)
2.jQuery Core Objects
**JQuery Object for short** is what gets returned from executing $()
Get the JQuery object: Executing the JQuery function returns the JQuery object
Use JQuery objects: $obj.xxx();
When called in parentheses, he is the function. If so, he is the object.
When to use objects and when to use functions?
Parentheses are functions. () is the use of objects
3.jQuery features
JQuery can use collection objects directly. Method operations default to the first line of the operation
JQuery can manipulate collections directly (except for pop-ups) and write with a concatenation
[External chain picture transfer failed, source may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-lJfcwjsW-163759926) (C:UsersshenjianAppDataRoamingTyporatypora-user-imagesimage-20233.png)]
JQuery Selector
**Base selector:**Base selector is the name of the base id, class, name, and so on.
**Hierarchical Selector: ** is the collective name of a sibling grandchild through a child's parent
Filter selector:
// $(function () { // alert('I don't know how many Jqueries') // }) // $(function () {//union selector // alert($("h1,h2").html()) // }) // $(function () {//global selector, get everything from the web page // alert($("*").html()) // }) // $(function () {//descendant selector // alert($("div a").html()) // }) // $(function () {//sub selector // alert($("div>a").html()) // }) // $(function () {//adjacent selector his next sibling selector // alert($("div+h1").html()) // }) // $(function () {//peer selector gets all tags for h1 of his peers // alert($("div~h1").html()) // })
Form selector:
β
/* Requirement: 1.Select unavailable text input boxes 2.Show the number of hobbies you choose 3.Show the selected city name */ //1. Select unavailable text input boxes $(':text:disabled').css('background',"red"); //: text:disabled Gets the input text box text Sets the background color to red for unavailable text boxes //2. Show how many checkbox es to choose your hobbies //$(': checkbox:checked').length //: Checkbox:checked Get input box is checkbox The number of boxes selected //3. Display the selected city name $(':submit').click(function()){ var city=$('select>option:selected').html()//Selected option's label body text city=$('select').val()//Value property value of selected o'ption }
Detailed description of JQuery base selector
type | grammar | describe | Return value | Example | |
---|---|---|---|---|---|
id selector | #id | Match elements based on specified id | Single Element | $("#content") Selects an element with an id name of content | |
Class selector | .class | Match elements based on the specified class name | Element Collection | $(".content") Selects an element whose class name is content | |
tag chooser | element | Match elements based on specified label names | Element Collection | $("p") Selects all P-Label elements | |
Global selector | * | Match all elements | Element Collection | $("*") Select all elements | |
Union selector | selector1,selector2,selector3 | Match each selector to the element merge and return together | Element Collection | $("div,p,#content") Selects all elements whose div, p, id are content |
Detailed description of JQuery filter selector
grammar | describe | Return value | Example |
---|---|---|---|
:first | Select the first element | Single Element | $("ul:first") Selects the first UL element of all UL elements |
:last | Select the last element | Single Element | $("ul:last") Selects the last UL element of all UL elements |
:not(selector) | Select all elements except the given selector | Element Collection | $("ul:not(.top)") Select UL element whose class is not top |
:even | Select an element whose index value is even, index starts at 0 | Element Collection | $("ul:even") Select UL elements whose index is even |
:odd | Select the element whose index value is odd, index starts at 0 | Element Collection | $("ul:odd") select the UL element whose index is odd |
:eq(index) | Select the element of a given index, starting with 0 | Single Element | $("ul:eq(0)") Selects UL element with index 0 |
:gt(index) | Select all elements smaller than the given index, starting with 0 | Element Collection | $("ul:gt(1)") Selects UL elements with an index greater than 1 |
:lt(index) | Select all elements smaller than the given index, starting with 0 | Element Collection | $("ul:lt(1)") Selects UL elements with an index less than 1 |
:header | Select all Title elements, such as h1~h6 | Element Collection | $(": header") Selects all the header elements in the page |
:focus | Select the element that currently gets focus | Element Collection | $(": focus") Selects the element that currently gets focus |
:animated | Select all animation elements | Element Collection | $(": animated") Selects all current animation elements |
Preventions and examples related to JQuery common attribute filter selectors
grammar | describe | Return value | Example |
---|---|---|---|
[attribute] | Select the element that contains the specified attribute | Element Collection | $("p[id]") Select the P element with the ID attribute |
[attribute=value] | Gets the element whose specified property is value | Element Collection | $("p[id=content]") Select the P element with the ID attribute of content |
[attribute!=value] | Gets the element whose specified property is not equal to value | Element Collection | $("p[id!=content]") Select the P element that contains an ID attribute that is not equal to the content |
[attribute^=value] | Gets the element whose specified property begins with value | Element Collection | $("p[id^=content]") Select the P element whose Id starts with content |
[attribute$=value] | Gets the element whose specified property ends with value | Element Collection | ( " p [ i d ("p[id ("p[id=content]") Select the P element whose Id ends with the content |
[attribute*=value] | Gets the element whose specified property contains value | Element Collection | $("p[id*=content]") Select the P element whose Id contains the content |
Tool method
-
<! -- 1. $ .each():Traversing through data 2 in an array or object.$.trim():Remove whitespace 3 from both sides of a string. $.type(obj):Get data of type 4.$.isArray (obj):Determine if it is array 5.$.isFunction(obj):Determine whether it is a function 2. $. parseJSON(json) :analysis json String to js object/array
JQuery Formula
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> </head> <!-- Formula: $(selector(selector)).action(); --> <body> <a href="#"Id=" test-jQuery ">dot Lao Zi</a> <script> document.getElementById('test-jQuery'); $('#test-jQuery').click(function () { alert('Hello jQuery') }) </script> </body> </html>
JS selector versus JQuey
<script> //Native js, few selectors, hard to remember //Label document.getElementsByTagName(); //id document.getElementById(); //class document.getElementsByClassName(); $('p').click();//tag chooser $('#id1').click(); $('.class1').click(); </script>
Online Document Tool Station: https://jquery.cuishifeng.cn/
Event
Mouse events, keyboard events, other events
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-MSSuPq67-164259927) (C:\UsersshenjianAppDataRoamingTyporatypora-user-imagesimage-202221271.png)]
Mouse Events (Mouse Move Events)
//Mosemove Mouse Move Event <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <style> #divMove { width: 500px; height: 500px; border: 1px solid red; } </style> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <body> <!-- Requirements: Get the current coordinate of the mouse--> mouse:<span id="mouseMove"> </span> <div id="divMove">Move your mouse here to try it </div> <script> $(function () { $('#divMove').mousemove(function (e) { $('#mouseMove').text('x:' + e.pageX + 'y:' + e.pageY) }) }) </script> </body> </html>
Operation DOM
$('#Test-ul li[name=python]'. text(); //get value $('#Test-ul li[name=python]'. text ('1dw'); //set value $('#test-ul').html(); //get value $('#Test-ul'). HTML ('<strong>132</strong>'); //Set value
Operation of css
$('#test-ul li[name=python]' ).css("color","red");
Display and hide of elements: intrinsic display=none;
$('#Test-ul li[name=python]'.Show(); //display $('#Test-ul li[name=python]'..hide(); // hide $('#Test-ul li[name=python]'.toggle()//Hide if it is shown Hide if it is hidden or show if it is hidden
Entertainment Test
$(window).width(); //Width of window $(window).height();//Get the height of window $(document).width(); //Width of file $(document).height();//Get the height of the file
Create Node
grammar
$("Label")
Example: var tr = $("<tr></tr>"); var td = $("<td name='name'></td>").html(name) var td1 = $("<td name='age'></td>").html(age); var td2 = $("<td name='position'></td>").html(zhiye); var td3 = $("<td name='mobile'></td>").html(shouji); var td4 = $("<td name='email'></td>").html(youx);
Insert Node
Insertion method | grammar | describe |
---|---|---|
Insert inside | append(a) | Inserts the specified content at the end of the matching element |
Insert inside | appendTo(a) | Appends the selected element to another specified set of elements |
Insert inside | prepend(a) | Inserts the specified content at the beginning of the matching element |
Insert inside | prependTo(a) | Preposition all matching elements within the set of specified elements |
External Insert | after(a) | Insert content after matching elements |
External Insert | insertAfter(a) | Inserts a matching element after another specified set of elements |
External Insert | bofore(a) | Insert content before matching elements |
External Insert | insertBefore(a) | Inserts a matching element before another specified set of elements |
Delete Node
grammar
Deleted Elements.remove([selector])//[selector] denotes an optional parameter Deleted Elements.detach([selector])//[selector] means that the optional parameter remove() is the same as detach() except that the detech() method retains data events associated with deleting elements when deleting them, and so on. Deleted Elements.empty() The method does not take any parameters, strictly speaking,.empty()Not deleting elements, but empty elements and their descendants
Replication Node
grammar
Replicated Node Elements.clone([includeEvents])//IncudeEvents is an optional parameter He is a Boolean type Default value is false to indicate whether to copy the current node ///Note that replicated nodes do not append elements You also need to append replicated nodes where you want to append them
Replace Node
grammar
$(selector).replaceWith(content) //They are all replacement nodes, the only difference is that they use this instead $(content).replaceAll(selector)
Node Property Operation
Getting and setting element properties
grammar
$(selector).attr(attribute)//Get property value $(selector).attr(attribute,value)//Setting individual property values $(selector).attr({attribute:value,attribute:value})//Setting multiple property values $(selector).removeAttr(attribute)//Attribute deletion of an element indicates the name of the attribute to be removed γ prop()yes jQuery 1.6 Starting with a new method, the official recommendation has true and false Attributes of two attributes, such as checked, selected perhaps disabled Use prop()οΌOther uses attr(). γγWe can put attribute Understand as "feature". property Understand as an attribute to distinguish the difference between the two.
Traverse Nodes
grammar
//Traversing through child elements: chidren([expr]) //expr is an optional parameter //Traversing through peer elements: next([expr])//Next level element used to get tight ridge matching elements //Traversing through sibling elements: prev([expr])//Previous element used to get tight ridge matching elements //Traversing through peer elements: siblings([expr])//used to get all peer elements before and after matching elements //Traversing through ancestor elements: parent([selector])//Gets the parent element of each matching element in the matching element //Traversing through ancestor elements: parents([selector]) //Gets the ancestor elements of each matching element in the matching element //Other traversal methods: $(selector).each(function(index,element){} traverses a collection through Subscripts element.val() //Get the value of an element element.text() //Get the text of an element element.html() //Get the html of the element
Set, Get Style Values
grammar
$(selector).css(name,value)//Setting a single css property $(selector).css({name:value,name:value})//Setting multiple css properties
Append, Remove Styles
$(selector).addClass(classname)//Setting a single class class class style $(selector).addClass(classname1 classname2 classname3)//Setting multiple class class class styles $(selector).removeClass(classname)//Remove single class class class style $(selector).removeClass(classname1 classname2 classname3)//Remove multiple class class class styles
Style Switching and Judgment
grammar
$(selector).toggleClass(calassname) //Switch class style $(selector).hasClass(calassname) //Determine if a class style exists
Mouse events
Method | describe | Execution timing |
---|---|---|
click | Click Event | On mouse click |
mouseover | Mouse Move In Event | When the mouse moves in |
mouseout | Mouse Move Out Event | When the mouse pointer moves out |
mouseenter | Mouse Entry Event | When the mouse pointer enters |
mouseleave | Mouse pointer departure time | When the mouse pointer leaves |
Keyboard events
Method | describe | Execution timing |
---|---|---|
keydown(function) | Attach event handler to keydown event | When keyboard keys are pressed |
keyup(function) | Attach event handler to keyup event | When keyboard keys are released |
keypress(function) | Attach event handler to keypress event | When a printable character is generated |
Browser Events
Method | describe | Execution timing |
---|---|---|
resize(function) | Attach event handler to resize event | When browser window size changes |
scroll(function) | Attach event handler to scroll event | When a scrollbar or scrollable element scrolls |
Form Events
Method | describe | Execution timing |
---|---|---|
focus([function]) | Attach event handler to focus | Element gets focus |
blur([function]) | Attach event handler to blur | Element loses focus |
change([function]) | Attach event handler to change event | When the value of an element changes |
submit([function]) | Attach event handler to submit event | The submit event applies only to elements and is triggered when the form is submitted |
Binding and Removal Events
Binding Events
1. Grammar
$(selector).on(event[,childselector],[,data],function); //Event is a required parameter indicating that if event types, click, mouseover, mouseout, etc. bind multiple events at once and restrict the same event handler, event should be split by a space //childselector is an optional parameter that filters the descendant elements of the selected element that triggers the event //Data is an optional parameter. Pass to event object as event.data property value //function is a required parameter that binds functions executed after triggering events
Remove Events
1. Grammar
$(selector).off(event[,childselector],function); //Event is a required parameter indicating that if event types, click, mouseover, mouseout, etc. bind multiple events at once and restrict the same event handler, event should be split by a space //childselector is an optional parameter that filters the descendant elements of the selected element that triggers the event //Data is an optional parameter. Pass to event object as event.data property value //function is a required parameter that binds functions executed after triggering events
Composite Events
What is a composite event? Columns such as the mouse pointer moved into the Show Level 2 menu, the mouse pointer removed the Hide Level 2 menu, and events can be completed more easily using the Match Event grammar 1.$(selector).hover(enterFunction,leaveFunction) grammar //Set Menu Style $("li").hover(function () { $(this).addClass("selected") },function () { //Syntax executed when removing $(this).removeClass() })
Common animation methods
1. Show and hide control elements
Grammar:
$(selector).show([speed][,easing][,fn]) display //Speed specifies display effects for optional parameters at a speed of 1000 milliseconds, slow, normal, fast //easing is an optional parameter that specifies how fast to get on different elements of the animation The default value is swing Possible values are linear swing moving slowly at the beginning and end of the animation Block moving slowly in the middle, linear mycetin moving slowly fn Specifies the method to be executed once after the animation is complete for the optional parameter, called once for each matching element $(selector).hide([speed][,easing][,fn]) hide
2. Change element transparency
fadein()Method control element fade in //Increase the opacity of an element for a specified period of time until it is fully displayed fadeOut()0//Method control element fades out until the element disappears completely grammar: $(selector).fadein()([speed][,easing][,fn]) $(selector).fadeOut()([speed][,easing][,fn])
3. Change element height
$(selector).slideup([speed][,easing],[,fn]); //Extend display from top to bottom $(selector).slideDOwn([speed][,easing],[,fn]);//From bottom to top
4. Custom Animation
Grammar: $(selector).animate({parms},speed,fn) //params is a required parameter that defines the css attribute of the animation //speed specifies the effect time for optional parameters //fn is an optional parameter, function executed after animation is complete
Form validation, regular expressions
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-hloZJkZr-163759929) (C:UsersshenjianAppDataRoamingTyporatypora-user-imagesimage-queue.png)]
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-OG01ctZ7-164296930) (C:UsersshenjianAppDataRoamingTyporatypora-user-imagesimage-2022.png)]
var usernameText = $('username').val(); // //var patt=new RegExp('e');// Indicates that the requirement string must contain the letter e // Var patt =/e/; // This also means that the requirement string must contain the letter e // patt.test(a) verifies that the substituted values meet my requirements // Var patt = /[a b c]/ // means to contain either a or b or C // var patt = /[A-Z]/Indicates whether a string is required to contain uppercase letters // var patt = /[a-z]/Indicates whether the string is required to contain lower case letters //The \w metacharacter is used to find a word string Word strings include a-z, A-Z, 0-9, and characters including underscores var a = "AAA "; var patt = /[a-z]/ //Indicates whether a string is required to contain lowercase letters if (patt.test(a)) { alert("legitimate") } else { alert('Wrongful') } })
Form Selector
grammar | describe | Return value |
---|---|---|
:input | Match all input, textarea, select, and button elements | Element Collection |
:text | Match all single-line text boxes | Element Collection |
:password | Match all password boxes | Element Collection |
:radio | Match all radio buttons | Element Collection |
:checkbox | Match all check boxes | Element Collection |
:submit | Match all submit buttons | Element Collection |
:reset | Match all Reset buttons | Element Collection |
:button | Match all buttons | Element Collection |
:image | Match all file fields | Element Collection |
:file | Match all file fields | Element Collection |
Form Filter Selector
grammar | describe | Return value |
---|---|---|
:enabled | Match all available elements | Element Collection |
:disabled | Match all non-elements | Element Collection |
:checked | Match all selected elements (check boxes, radio buttons, drop-down lists) | Element Collection |
:selected | Match the selection element selected by select | Element Collection |
regular expression
Regular expressions, also known as regular expressions, are powerful tools for performing pattern matching on strings. The matching pattern can be divided into simple mode and complex mode.
Definition of regular expressions
Common way
var reg=/Expression Rules/Additional parameters; Where the expression rule is a string used to describe the search pattern of the regular expression, the additional parameters are optional, to extend the meaning of the expression, and the following parameters are acceptable: 1. g:Indicates that a global match can be made, defaulting to a non-global match, matching only the first string that meets the requirements 2. i:Indicates case insensitive matching 3. m:Indicates that multiple lines can be matched var reg1=/pink/; var reg1=/pink/g; var reg1=/pink/gi;
How to construct a function
var reg=new RegExp('Expression Rules','Additional parameters');
Expression Rules
Method of RegExp object
Method | describe |
---|---|
exec | Retrieves the partition of a regular expression within a character, returns the value found, and determines its location |
test | Retrieves the value specified in the string, returning true or alse |
Method of String Object
Method | describe |
---|---|
match | Find a match for one or more regular expressions |
search | Retrieve values that match regular expressions |
replace | Replace strings that match regular expressions |
split | Split a string into an array of strings |
HTML5 Form Validation New Properties
attribute | describe |
---|---|
placeholder | Provides a hint that displays when the input field is empty and disappears when the focus input is received |
required | Specifies that the input field cannot be empty |
pattern | Specifies the pattern (regular expression) for validating the input field |
Example
<input type="text" id="uName" placeholder="English, numeric length 6-10 Characters" required pattern="[a-zA-Z0-9]{6,10}" /> <input type="password" id="pwd" placeholder="6 Length-16 Characters" required pattern="[a-zA-Z0-9]{6,16}"/>
validity attribute application
When form elements add validation attributes required and pattern ed, the validityState object provided with HTML5 can be used to obtain the validation status of the current validation attribute
attribute | describe |
---|---|
valueMissing | When the required property is set on a form element, the form cannot be validated if the value of the form is empty |
typeMismatch | Returns true if the user's input does not match the form type; Otherwise, return false |
patternMismatch | Returns true if the user's input does not match the positive patterm property of the form element; Otherwise, return false |
tooLong | Returns true when user input exceeds the character length specified by the form element maxLength attribute; Otherwise, return false |
rangeUnderflow | Returns true when the value entered by the user is less than the value of the min attribute; Otherwise, return false |
rangeOverflow | Returns true when the value entered by the user is greater than the value of the max attribute; Otherwise, return false |
stepMismatch | Returns true if the value entered by the user does not conform to the rule inferred by the step attribute; Otherwise, return false |
customError | When using a custom validation error prompt, return true when a custom error message exists: otherwise, return false |
Agax to learn in the future; ajax();
$('#from').ajax() // What do you look like if you succeed and what do you look like if you fail? $.ajax({ url: "test.html", context: document.body, success: function(){ $(this).addClass("done"); }});
ES6 New Features
Destructuring assignment
ES6 allows you to extract values from arrays, assign values to variables by location, and deconstruct objects
Array Deconstruction
//code implementation let [a,b,c]=[1,2,3]; //One-to-one correspondence console.log(a) console.log(b) console.log(c)
Object Deconstruction
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-J0K0rd93-164296932) (C:UsersshenjianAppDataRoamingTyporatypora-user-imagesimage-2021.png)]
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-S0rd7AtA-164296933) (C:UsersshenjianAppDataRoamingTyporatypora-user-imagesimage-20222188.png)]
Arrow function
New way to define functions in ES6
()=>{} //() Method body with parameters {} let fn =()=> {console.log(123) } fn()
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-Cb2yU5ZM-163796934) (C:UsersshenjianAppDataRoamingTyporatypora-user-imagesimage-queue 2.png)]
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-58giIUN5-164296935) (C:UsersshenjianAppDataRoamingTyporatypora-user-imagesimage-2021.png)]
//Arrow function does not bind this arrow function does not have its own this keyword If the arrow function uses this this this keyword to point to this in the location defined by the arrow function
The following interview question this points to obj's object obj is nothing and then finds it empty inside obj
You can then define an age globally to find it
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-nfaligtI-164296936) (C:UsersshenjianAppDataRoamingTyporatypora-user-imagesimage-202803.png)]
Remaining function
[External chain picture transfer failed, source may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-UkpqIEvJ-163796937) (C:\UsersshenjianAppDataRoamingTyporatypora-user-imagesimage-2029.png)]
array extension method
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-6THJxczI-164296938) (C:UsersshenjianAppDataRoamingTyporatypora-user-imagesimage-2023.png)]
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-sY4s2iNl-163796938) (C:UsersshenjianAppDataRoamingTyporatypora-user-imagesimage-20251074.png)]
Extensions to built-in objects
1. Module string
Embedding variables in strings
// let name ='shen jian'; // let name1 ='father'; // // document.write(`I'm Chen Ji's big dad ${name}</br> // I am Chen Jin's second father ${name}</br> // I'm Chen Yin's third father ${name1} // `);
2. New string manipulation method [external chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-CPNL5sJw-164259939) (C:UsersshenjianAppDataRoamingTyporatypora-user-imagesimage-20205229;29.png)]
3. Extension of Arrays
1. Extended Operators
Extension operators use three dots (...) to convert an array to a comma-separated sequence
grammar
...array
2.Array.from (method) [External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-YXSFpkcm-164259940) (C:UsersshenjianAppDataRoamingTyporatypora-user-images2020505499;.png)]
// // let arr4 = Array.from(set); //convert set combinations to coincident merged arrays // let set1=new Set(['red','green',['blue']]) // for (let item of set1.keys()) {//return key // document.write(item) // } // For (let item of set1.values (){// Returns the value created // document.write(item) // } // For (let item of set1.entries(){//return key-value pairs // document.write(item) // } // document.write(arr4)
3. Array traversal method
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-RbBaKeSh-164296941) (C:UsersshenjianAppDataRoamingTyporatypora-user-imagesimage-20251.png)]
// // let arr4 = Array.from(set); // Convert set combinations to coincident merged arrays // let set1=new Set(['red','green',['blue']]) // for (let item of set1.keys()) {//return key // document.write(item) // } // For (let item of set1.values (){// Returns the value created // docu![image-20211105223028675](C:\Users\shenjian\AppData\Roaming\Typora\typora-user-images\![image-20211105223054001](C:\Users\shenjian\AppData\Roaming\Typora\typora-user-images\image-20211105223054001.png)image-20211105223028675.png)ment.write(item) // } // For (let item of set1.entries(){//return key-value pairs // document.write(item) // } // document.write(arr4)
Extension of object
let name='Xiao Ming'; let birth='2001/12/23'; //longhand const Person={ name:name, birth:birth } //Concise writing const Person={ name, birth }
1. Object New Methods
grammar
Object.is() Method //Comparing strict equality of successions is essentially consistent with es5 ===
2.Objece.assign() method
grammar
Objece.assign() //Method is used for merging objects. First, the target object is followed by the source object for merging and de-duplicating objects
Code implementation:
let objOne = {a: 1}; let objTwo = {b: 4}; let objThree = {b: 4, c: 5}; Object.assign(objOne, objTwo, objThree) let bbb = {...objOne, ...objTwo, ...objThree} console.log(objOne) console.log(Object.assign(bbb))
3. Traversal methods of objects
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-5jxKyFF1-1637425996942).) file:///C: UsersshenjianDocumentsTencent Files11761696ImageC2CD79921CDCE608C368D19259EF01BBA6C.png)]
Set and Map Objects
Concepts:
Set objects have data structures similar to arrays, but members have unique values and no duplicate values, so they can be used to weight
grammar:let set=new Set(array) // let arr1 = [1, 2, 3, 4, 5] // let arr2 = [1, 2, 3, 4, 5, 10] // Let arr3 = [... arr1,... Arr2] // splice two arrays // let set = new Set(arr3); //Convert Enron to set
Common properties and methods of Set objects
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-9QTMJxzp-1637425996943).) file:///C: UsersshenjianDocumentsTencent FilesC2C6E16B9D9D33B6073F8155F8DFEFE09.png)]
Set Add-Remove Check
// // // // set.add(12)//Add a value // //set.delete(10)//delete a value // // / set.clear()// know all members, no return value // //set.has(1)//Returns a Boolean value indicating whether the value is a member of the set // // set.size//get the length of the set // // let arr4 = Array.from(set); //convert set combinations to coincident merged arrays // let set1=new Set(['red','green',['blue']])
Map object
Concepts:
Map objects exist as key-value pairs, and all types can be used as keys
// let set = new Map([[1,'Shenjian'], [2,'Shenjian'], [3,'Chen Ji'])//Grammar implementation
Common properties and methods of Map objects
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-VH9LOVLm-1637425996944).) file:///C: UsersshenjianDocumentsTencent Files11761696ImageC2C877BBD48B07B2E7F0B02FEA9E.png)]
Module Syntax
export and import commands
1.export is export
export {area, circumference}
2.import Import
import{area,circumference} from './circle.js'
document.write(item) // } // For (let item of set1.values (){// Returns the value created // docu![image-20211105223028675](C:\Users\shenjian\AppData\Roaming\Typora\typora-user-images\![image-20211105223054001](C:\Users\shenjian\AppData\Roaming\Typora\typora-user-images\image-20211105223054001.png)image-20211105223028675.png)ment.write(item) // } // For (let item of set1.entries(){//return key-value pairs // document.write(item) // } // document.write(arr4)
### Extension of object ```javascript let name='Xiao Ming'; let birth='2001/12/23'; //longhand const Person={ name:name, birth:birth } //Concise writing const Person={ name, birth }
1. Object New Methods
grammar
Object.is() Method //Comparing strict equality of successions is essentially consistent with es5 ===
2.Objece.assign() method
grammar
Objece.assign() //Method is used for merging objects. First, the target object is followed by the source object for merging and de-duplicating objects
Code implementation:
let objOne = {a: 1}; let objTwo = {b: 4}; let objThree = {b: 4, c: 5}; Object.assign(objOne, objTwo, objThree) let bbb = {...objOne, ...objTwo, ...objThree} console.log(objOne) console.log(Object.assign(bbb))
3. Traversal methods of objects
[img-5jxKyFF1-1637425996942)]
Set and Map Objects
Concepts:
Set objects have data structures similar to arrays, but members have unique values and no duplicate values, so they can be used to weight
grammar:let set=new Set(array) // let arr1 = [1, 2, 3, 4, 5] // let arr2 = [1, 2, 3, 4, 5, 10] // Let arr3 = [... arr1,... Arr2] // splice two arrays // let set = new Set(arr3); //Convert Enron to set
Common properties and methods of Set objects
[External Chain Picture Transfer... (img-9QTMJxzp-1637425996943)]
Set Add-Remove Check
// // // // set.add(12)//Add a value // //set.delete(10)//delete a value // // / set.clear()// know all members, no return value // //set.has(1)//Returns a Boolean value indicating whether the value is a member of the set // // set.size//get the length of the set // // let arr4 = Array.from(set); //convert set combinations to coincident merged arrays // let set1=new Set(['red','green',['blue']])
Map object
Concepts:
Map objects exist as key-value pairs, and all types can be used as keys
// let set = new Map([[1,'Shenjian'], [2,'Shenjian'], [3,'Chen Ji'])//Grammar implementation
Common properties and methods of Map objects
[img-VH9LOVLm-1637425996944)]
Module Syntax
export and import commands
1.export is export
export {area, circumference}
2.import Import
import{area,circumference} from './circle.js'