当前位置:网站首页>JS fighting on...
JS fighting on...
2022-06-12 22:18:00 【The nth day of not loving oranges】
I'm really desperate this week , After a nap, I feel like I have forgotten everything , This feeling makes people crazy , act strangely , So what can I do , There is no such thing as jumping out of the boat when you get on the thief's clothes .
The first day :
1、ES5:
(1) The object of protection : Protect members of objects ( Properties and methods )
How to protect :
① Four characteristics :
Object.defineProperties(obj,{
" Property name ":{
value: Actual saved value ,
writable:true/false, // Controls whether this property is modified
enumerable:true/false, // Controls whether this property is for in Loop traversal
configurable:true/false, // Controls whether this attribute is deleted Main switch , Once set false, Other features are not allowed to be modified , Once set false, Irreversible .
}
})
② Three levels :
a、 Anti expansion : Prohibit adding new properties to objects :Object.preventExtensions(obj);
b、 seal up : It is forbidden to add new attributes to objects and delete attributes :Object.seal(obj);
c、 frozen : Adding... To an object is prohibited 、 Delete 、 Modify properties :Object.freeze(obj);
(2) New of array API:
① Judge : The result is a Boolean value
every: every last , Every element is required to meet , The result is true, As long as there is one unsatisfied, it is false, Be similar to &&
grammar :
var bool = arr.every(function(val,i,arr){
return Judge the condition ;
})
some: One of them , Every element is required to be unsatisfied , The result is false, As long as there is one satisfaction, it is true, Be similar to ||
grammar :
var bool = arr.some(function(val,i,arr){
return Judge the condition ;
})
② Traverse : Take each element out of the array and perform the same or similar operations
forEach: Traversal array , Modify the original array directly
grammar :
arr.forEach(function(val,i,arr){
Do the operation directly ;
})
map: Traversal array , Do not modify the original array , Returns a new array
grammar :
var newArr = arr.map(function(val,i,arr){
return Operating results ;
})
③ Filter and aggregate
Filter : Filter out what you want , But the original array will not be modified
grammar :
var subArr = arr.filter(function(val,i,arr){
return Judge the condition ;
})
Summary : Put together each element in the array
grammar :
var sum = arr.reduce(function(prev,val,i,arr){
return prev+val;
}, Base value );
(3)Object.create(); // Create child objects from parent objects , Inheritance has been set up
grammar :
var Sub object = Object.create( parent object ,{
" Own attribute name ":{ Four characteristics },
.................
})
(4) During the interview : Strict mode
Turn on : Add... At the top of any scope :"use strict";
function :① Do not assign values to undeclared variables -- Solve the problem of global pollution
② Silent failure is upgraded to an error
(5)call/apply/bind: You can't use your own method
①call / apply : Temporarily replaced... In the function this--- To borrow ( It is equivalent to calling the function immediately , Execute immediately )
grammar : Function name .call( Borrowed objects , Actual parameters ,...); ---- Pass in each argument individually
Function name .apply( Borrowed objects ,arr); --- Only one array argument can be passed in ,apply Will break the array into individual elements
②bind : Permanently replaces... In the function this
a: Created a new function with exactly the same function as the original function
b: In the new function this Permanently bind to the specified object , Others cannot borrow it
c: Permanently fix some parameters in the new function
usage :var New functions = Primitive function .bind( The specified object , Permanent arguments ,...); // Not immediately , You need to call
emphasize :bind The bound new function cannot be call apply Borrow it
Fixed routine :
①Math.max/min.apply(Math.arr);
②Object.prototype.toString.call/apply(arr);
③ Class array to normal array : Class array name = Array.prototype.slice.call/apply( An array of class );
2、ES6 simplify EMCAScript
(1) Template string : You can put variables in a string -- There is no need to do string splicing , A simple... Is implemented in a string js Environmental Science
grammar :` My name is ${name}`
(2) Block level scope :
let Variable name = value ;
effect :① It is forbidden to declare in advance
② Added block level scope , One {} It's a block , Variables can only be used in definitions
③ The subscript of the element that records the current trigger event
(3) Arrow function
The formula : Get rid of function,() and {} In between =>, If there is only one formal parameter , Omit (), If function body has only one sentence , Omit {}, The function body has only one sentence and is return,return and {} All omitted
Never simplify events
the second day
1、 What is? DOM:Document Object Model( Document object model )
Put each label / Elements / attribute / Text / notes , As a DOM node / Elements / object , Provides some attributes and methods of operation elements .
2、DOM Trees :document, There is only one page document object , By the browser JS The interpreter automatically generates , Each one can be found by the root of the tree DOM Elements , node , object , It provides a lot of APT
3、 Every DOM Every element has three properties
(1)xx.nodeType: Describe the type of node
document node :9;element node :1;attribute:2;text node :3
(2)xx.nodeValue: The value of the property node , Get attribute value
(3)xx.nodeName: Name of node -- Judge xx What's the label
Be careful : The return is a fully capitalized winning signature
(4) recursive : The function itself is called again in the function , Sooner or later it will stop
When to use : Traverse DOM Trees , It is specially used to traverse the case where the level is not clear
How to use :
function Function name (){
① What should be done on the first floor? Do it directly ;
② Judge whether it has a next level , If the next level calls this function again , But the argument passed in is its next time ;
}
shortcoming : Start a large number of function calls at the same time , Waste of memory
4、 Traversal levels are ambiguous API:TreeWalker: In a DOM People walking on trees ,
shortcoming : Specifically for traversal levels that are ambiguous DOM Get ready
how :
Fixed formula :
① establish tw:
let tw=document.createTreeWalker( Root element ,NodeFilter.SHOW-ELEMENT);
② Call again and again nextNode Method to find each element -》 Cannot find for null
while((node=tw.nextNode())!=null){
node What to do ;
}
5、API Find elements directly
(1) adopt HTML Some of the features of go for elements
①id:var elem=document.getElementById("id"); - Found a single element , Did not find null
②tagname/class/name:
var elems=document.getElementsByTagName/ClassName/Name(" Tag name /class name ");- Found a set , Empty set not found
Suggest : Form control elements should not be written class, Because it is necessary to write name
(2) adopt css Selector to get elements :
① Single element :var elem=document.querySelector(" arbitrarily css Selectors ");
② Multiple elements :var elems=document.querySelectorAll(" arbitrarily css Selectors ");
Interview questions :getXXX and querySelectoXXX What's the difference? ?
The results are different :
1、getXXX, What is returned is a dynamic collection HTMLCollection
2、querySelectoXXX, What is returned is a static collection NodeList
Dynamic collection vs Static collection
1、 Dynamic collection : according to DOM The change of the tree , It is the dynamic set that also changes , Every modification DOM Trees , Will quietly find again DOM
shortcoming : Every time, I will quietly search again , Low efficiency , Out of commission forEach
2、 Static collection : Every modification DOM Trees , Static collections do not change , You will only recognize the first result you find when you are looking for it
advantage : Each time, it will not search again quietly , More efficient , have access to forEach
On the third day
1、 Content of element :
*1、elem.innerHTML: Gets or sets the value between the start tag and the end tag HTML Code , No compatibility issues , Can identify labels
obtain :elem.innerHTML
Set up :elem.innerHTML=" New content "
2、elem.textContent: Gets or sets the plain text between the start tag and the end tag , With compatibility issues , The label is not recognized
obtain :elem.textContent
Set up :elem.textContent=" New content "
* The old IE:elem.innerText;// The first time I met a junior , Originally, only the old IE Can be used , But with the development of various browsers ,IE There is no accommodation for everyone , Instead, other mainstream browsers make do with the old IE
*3、input.value: Gets or sets the single label ( A single label that can write content ) The content of
obtain :input.value;
Set up :input.value=" New content "
2、 Attribute of element :
*1、 Get attribute value :
The core DOM:elem.getAttribute(" Property name ");
HTML DOM:elem. Property name ;
*2、 Setting property values
The core DOM:elem.setAttribute(" Property name "," Property value ");
HTML DOM:elem. Property name =" Property value ";
*3、 Delete attribute :
The core DOM:elem.removeAttribute(" Property name ");
HTML DOM:elem. Property name ="";
4、 Judgment properties : The garbage , Can only judge whether there is , Can't judge what it is
The core DOM:elem.hasAttribute(" Property name ");
Really want to judge , More recommended :
if(elem.getAttribute("class")=="d1"){
Using the method of acquisition can determine what it is class
}
emphasize :HTML DOM It's really simple , But we need to pay attention :
1、class Written as className
2、 Only standard properties can be manipulated , Cannot manipulate custom attributes
3、 When deleting , The deletion is not clean , Some attributes can still be used if they are not deleted , such as href No attribute value defaults to refresh 、disabled Even if there is no attribute value, the operation is still disabled ..., Use the core when deleting with recommendations DOM
3、 Style of element :
1、 inline style : The highest priority , Other styles will be overwritten
Only the current element is available , Will not pull a whole body
Get style :elem.style.css Property name
Set the style :elem.style.css Property name ="css Property value "
The only drawback : When getting styles , You can only get inline styles
2、 Style sheets :
//1、 Get the stylesheet you want to manipulate
var sheet=document.styleSheets[1];
//2、 Get all the style rules in this style sheet
var rules=sheet.cssRules;
//3、 Count the style rule you want to operate on
var rule=rules[30];
//4、 operation : Get and set
console.log(rule.style.background);
rule.style.background="purple"
The fourth day :
1、BOM:Browser Object Model: Browser object model : Dedicated to operating the browser API, There is no standard ( Most browsers are unified API, Except for old IE),BOM Use less
a key : Timer 、 Event object event
2、window Introduction of objects : Play 2 A character
1、 Instead of ES Medium global, Act as a global object
2、 It also has some properties and methods , Refers to the current window itself
3、window Object provides something :
1、 How web pages open new links :4 Kind of
1、 Replace the current page , You can step back :
HTML:<a href="url"> Content </a>
JS:open("url","_self");
2、 Replace the current page , No retreat : - scene : E-commerce website : After payment , No retreat
history object : Records the history of the current window , Only with history can we move forward and backward
location object : Record the opening of the current window url, He has a method called substitution , No history will be generated
JS:location.replace(" new url");
3、 Open in new window , You can open multiple :
HTML:<a href="url" target="_blank"> Content </a>
JS:open("url","_blank");
4、 Open in new window , Only one :- scene : E-commerce website : Only one payment page is allowed to open
HTML:<a href="url" target=" Customize name"> Content </a>
JS:open("url"," Customize ");
intend : Each window has a name at the bottom , If you reopen the same name, The newly opened window will be replaced by the corresponding window ,_self-> The name of your own window ,_blank-> Create a new random name
summary :
1、HTML What can be done ,JS Can do it ,JS What can be done ,HTML Not necessarily
2、 Different jump methods , It can enhance the user's sense of experience
Expand :a The role of labels :
1、 Jump
2、 Anchor point
3、 download :<a href="xx. Installation suffix / Compression package suffix "> Content </a>
4、 open :<a href="xx.txt/ Picture suffix "> Content </a>
5、 Direct writing javascript:<a href="javascript:js sentence ;"> Content </a> - You do not need to bind click events
2、window Properties and methods provided :
attribute : Get the full size of the browser :outerWidth/Height;
* Get the size of the document display area in the browser :innerWidth/Height; - body Size
Get the full size of the screen :screen.width/height;
Method :1、 open windows :var newW=open("url","target/ Customize ","width=,height=,left=,top=");
Be careful :1、 When the third configuration parameter is not passed in , The size is the same as the browser , And glued to the browser , But if you have a third parameter , Out of browser
2、 The width and height cannot be set too small
2、 close window :window/newW.close();
3、 Change the size of the window :newW.resizeTo(newW,newH);
4、 Change the position of the window :newW.moveTo(x,y);
Expand :*** Get the mouse position :2 Step
1、 Pass a formal parameter in the parentheses in the event function e, Get the event object automatically event
2、 Get coordinates :
e.screenX/Y - The coordinates of the mouse relative to the screen : Even if the mouse is on the top 70px about
e.clientX/Y - Coordinates of the mouse relative to the document display area : Web pages, no matter how long or big , Always top is 0, At the bottom is 900 many
*e.pageX/Y - The coordinates of the mouse relative to the entire page - Follow our web changes
Complete the mouse following animation :
1、window/document.onmousemove - Moving the mouse anywhere on the page triggers
2、js The loading speed of is faster than that of the picture , Use load events :onload
3、***** Timer :2 Kind of
*1、 Periodic timer : Every once in a while , Will execute the operation in the timer once
Turn on :timer=setInterval(callback, In milliseconds )
stop it :clearInterval(timer);
2、 One time timer : Wait for a while , The operation in the timer is stopped once
Turn on :timer=setTimeout(callback, Wait milliseconds )
stop it :clearTimeout(timer);
Be careful : The one-time and periodic bottom layers are the same , It can even be converted to each other , So you can use either one
summary : function and loop and Timer Can be executed repeatedly , difference ?
1、 function - The user triggers a binding event
2、 loop - It's almost over in an instant
3、 Timer - Do it once in a while
边栏推荐
- MySQL introduction and installation (I)
- Oracle livelabs experiment: introduction to Oracle Spatial
- JVM Basics - > What are the thread shared areas in the JVM
- Create a virtual thread using loom - David
- Xingda easy control modbustcp to profibusdp
- Ansible roles project case (IV)
- Palindrome linked list and linked list intersection problem (intersecting with Xinyi people) do you really know?
- MySQL体系结构及基础管理(二)
- List of open source alternative projects of world famous Cloud Service SaaS companies
- JVM foundation > CMS garbage collector
猜你喜欢

JVM Basics - > how to troubleshoot JVM problems in your project

C # reading table data in word

JVM Basics - > how GC determines that an object can be recycled

JVM foundation > G1 garbage collector

Flutter series part: detailed explanation of GridView layout commonly used in flutter

SQL tuning guide notes 14:managing extended statistics

SQL tuning guide notes 13:gathering optimizer statistics

NoSQL - redis configuration and optimization (II) high availability, persistence and performance management
![[image denoising] image denoising based on trilateral filter with matlab code](/img/f2/770a0e2938728e731c18c0a66f7c12.png)
[image denoising] image denoising based on trilateral filter with matlab code

Ansible基础和常用模块(一)
随机推荐
Use group_ Dplyr issues when using group_ by(multiple variables)
MySQL introduction and installation (I)
Mr. Sun's version of JDBC (21:34:25, June 12, 2022)
关于 安装Qt5.15.2启动QtCreator后“应用程序无法正常启动0xc0000022” 的解决方法
【Proteus仿真】简易数码管定时器时钟
C # reading table data in word
Can tonghuashun open an account? Is it safe to open an account in tonghuashun? How to open a securities account
Ansible Roles-项目案例(四)
[sword finger offer] sword finger offer 58 - ii Rotate string left
最近公共祖先问题你真的学会了吗?
JVM Basics - > What are the thread shared areas in the JVM
Role of volatile keyword
JVM foundation - > three ⾊ mark
[simple] 155 Minimum stack
June training (day 12) - linked list
What is the difference between a user thread and a daemon thread?
Ansible playbook and variable (II)
Generate the chrysanthemum code of the applet (generate the chrysanthemum code, change the middle logo, change the image size, and add text)
The programmer dedicated to promoting VIM has left. Father of vim: I will dedicate version 9.0 to him
Unity 常用3D数学计算