当前位置:网站首页>JS continues to explore...
JS continues to explore...
2022-07-03 13:55:00 【The nth day of not loving oranges】
This week is no less difficult than the first week , Sure enough, only comparison can hurt , Every time you pick your head, you are also self-motivated , The process is difficult , But it must be cool to stick with it !!! review ing...
1、 Data type conversion :
1、 Cast :
1、 Turn the string :2 Kind of
1、xx.toString();//undefined and null Out of commission ,
2、String(xx);// Not as good as +""
2、 Turn numbers :
1、*parseInt(str/num) - Specially used for converting strings to integers
Execution principle : Read each character from left to right , Stop when you encounter non numeric characters , I don't know the decimal point , I met someone I didn't know , Then for NaN
2、*parseFloat(str) - Specially used for converting strings to floating-point numbers
Execution principle : Almost and parseInt Agreement , But know the first decimal point
3、Number(xx);// Not as good as *1 /1 -0
3、 Turn bull :
Boolean(xx);// Omnipotent , Anyone can turn it into a Boolean value , Simplified version :!!xx - The simplified version won't work
* Which will be false?6 individual :0,"",undefined,null,NaN,false, The rest are true
2、 Implicit conversion : Most of them are in operators
2、*** Operators and Expressions
1、* Arithmetic operations :+ - * / %
Implicit conversion : Default , Turn to numbers , In the operation
special :1、+ operation , Just touch a string , Then it becomes splicing
2、- * / %, A string of pure numbers , It can also be converted into numbers , But the string of non pure numbers is converted to NaN
NaN The result of participating in any arithmetic operation is still NaN
2、* Comparison operations :> < >= <= == != === !==
result : Boolean value
Implicit conversion : Default , Both sides will quietly turn into numbers , Compare again
special :
1、 If left or right 【 Both sides 】 All the strings involved in the comparison , It is bitwise PK Hexadecimal of each character unicode Number ( Decimal system ascii code )
0-9<A-Z<a-z< Chinese characters
2、NaN The result of any comparison operation is false, With a question , There is no way to use ordinary comparison operations to judge a xx Is it right? NaN
solve :!isNaN(xx); true-> Significant figures false->NaN
3、undefined==null,
problem :== I can't tell you apart undefined and null, How can we distinguish ?
undefined===null
3、* Logical operators :
Implicit conversion : Quietly, it turns into Boolean , Then we draw a conclusion through comprehensive comparison
&&: All conditions are true, The result is true
Just one for false, The results for false
||: All conditions are false, The result is false
Just one for true, The results for true
!: Invert Boolean values
special : usage
*** Short-circuit logic : As long as the former condition has been able to draw a final conclusion , Then the subsequent conditions will not be implemented !
&& A short circuit : If the former condition is true, The latter operation is executed
If the former condition is false, The latter operation is not executed
To simplify the 【 ordinary 】 Branch :if( Conditions ){ operation }
grammar : Conditions &&( operation );
give an example : once :if(total>=500){total*=0.8};
Now? :total>=500&&(total*=0.8);
special :1、【 ordinary 】-> The operation can only have one sentence
|| A short circuit : If the former condition is true, There is no need to execute the latter
If the former condition is false, You need to execute the latter
4、* The assignment operation : In one sentence, two operations are performed , Calculate first , To assign a value
+= -= *= /= %= ++ --
When to use : Just take out the value in the variable , I'm doing calculations , And then when you save it back , Try the assignment operation
i=i+1;
recommend :
i+=1 perhaps i++;
Increasing :i++; You can only +1
Add up :i+=n; I want to add a few at a time , whatever
++ It is divided into ++i and i++
1、 When used alone , Not participating in other expressions , It's the same before and after
2、 If other expressions are involved :
In fact, the values in variables will +1
++i, What is returned is incremented 【 The new value 】
i++, What is returned is the one before increment 【 The old value 】
5、*** Three mesh operation : Simplify branches :if(){}else{} if(){}else if()else{}
grammar :
1、 Conditions ? operation 1: Default operation ;
2、 Conditions 1? operation 1: Conditions 2? operation 2: Default operation ;
1、***** Customize Function:
What is a function : You need to define , A code snippet that can be used repeatedly
When to use :1、 I don't want to open the page and execute it immediately 2、 It can be used repeatedly in the future 3、 Want to bind to page elements
How to use :
1、 Create and call :2 Kind of
1、 establish
*1、【 Declaration method 】 Create a function
function Function name ( Shape parameter ,...){
The body of the function ;
return Return value / result ;
}
2、【 Direct measurement 】 Create a function - It's useless
var Function name =function( Shape parameter ,...){
The body of the function ;
return Return value / result ;
}
2、 call
var Catch the returned result = Function name ( Actual parameters ,...);
// Actually return The intended exit function of , But if return Followed by a data ,
// By the way, return the data to the outside of the function scope , but return Only responsible for returning , Not responsible for saving
// Even if omitted return, By default return undefined;
// Do you need to get the result of the function , Look at yourself
2、*** Scope :2 Kind of
1、 Global scope : Global variables and Global function , It can be used anywhere on the page
2、 function / Local scope : local variable and Local function , stay 【 Available internally when the current function is called 】
* Rules for using variables : Give priority to your own , I didn't find the overall situation , There is no error in the overall situation
special : shortcoming :1、 Never assign values directly to undeclared variables in functions - Global pollution
2、 Local can use global , But the whole cannot be local - solve : Look at it return
3、*** A statement in advance :
Before the procedure is formally carried out
take var Declared variables ( light ) and function Declared function ( heavy )
Will be quietly defined at the top of the current scope
But assignment remains in principle
4、*** Pass by value : Assignment between two variables :
If the value of the original type is passed :
Modify a variable , The other variable is unaffected
If you pass an object of reference type :
Modify a variable , Another variable will be affected , Because the operation is actually the same 【 Address values 】
2、 Predefined global functions : Predecessors created good methods in advance , Programmers can directly use , Can be used anywhere
1、 Encoding and decoding :
code :var code=encodeURIComponent(" World of warcraft ");
decode :var original text =decodeURIComponent(code);
2、isFinite(num): Judge num Is it infinite ,true-> Significant figures false-> infinity
Which will be false:NaN,Infinity, The denominator is 0
3、 Grisliness :parseInt/Float、isNaN、eval
eval(str): Compute string , Simply put, take off your clothes
3、* Branching structure :if Branch switch Branch
grammar :
switch( Variable / expression ){
case value 1:
operation 1;
case value 2:
operation 2;
default:
Default operation ;
}
special :1、case Without implicit conversion
2、 problem : There is only one by default case When satisfied , Will finish all the following operations
solve :break;
Suggest : every last case All operations are followed by one break
In some places, it is not necessary to add break:
1、 The last operation default It can be omitted break;
2、 If there are multiple conditions in the middle , The operation is the same , Don't need to,
3、default It can be omitted , If the conditions are not met , I can't do anything
Interview questions :if vs switch
1、switch...case... shortcoming : You must know the results of preparation before you can use , You can't judge the scope
benefits : Relatively efficient execution
2、if...else shortcoming : Execution efficiency is relatively low
advantage : It can be range judgment
Suggest : Code optimization , Try to if...else Switch to switch...case、 Three orders
Expand :JS Animation : Almost and JS irrelevant , And CSS of (transition transition )
JS Operation style , Instantly effective , Just add the transition and it will take effect slowly - animate.css Animation library ( library : A lot of animation )
1、*** Loop structure :
1、while( The loop condition ){ The loop body }
2、do{ The loop body }while( The loop condition )
Interview questions :while and do...while The difference between
Only for the first time : If everyone is satisfied for the first time , There is no difference between the two
If you are not satisfied for the first time ,while Not once ,dowhile At least once
3、***for( Loop variable ; The loop condition ; Changes in variables ){
The loop body ;
}
4、 Flow control statement : Exit loop :break;// Exit the whole cycle
continue;// Exit this cycle , Analyze according to the needs, which one to use
2、***** The basis of arrays :
1、 Basic concepts :
What is an array : In a memory ( Variable ) A collection structure in which multiple data are stored
when : As long as multiple related data are stored , All of them should be saved in an array ;
2、 establish :2 Kind of
1、* Direct measurement :var arr=[ value 1,...];
2、 Constructors :var arr=new Array( value 1,...);
The second way :var arr=new Array(num);// Create a length num Empty array of
3、 visit : Array name [ Subscript ]; -- The current element
add to / modify : Array name [ Subscript ]= The new value ;
special : Read elements , The subscript crossing the line -- return undefined
Additive elements , The subscript crossing the line -- Subscripts are not continuous , Resulting in a sparse array
4、 There are three unrestricted arrays
1、 Unlimited length
2、 No restrictions on type
3、 Unrestricted subscript out of bounds
5、 Array unique attribute : Array name .length: Get the length of this array
Three fixed routines :
1、 Add... At the end :arr[arr.length]= The new value ;
2、 Get penultimate n individual :arr[arr.length-n];
3、 Delete countdown n individual :arr.length-=n
6、 Traversal array : Perform the same for each element in the array or Similar operation
for(var i=0;i<arr.length;i++){
arr[i];// Current secondary element
}
7、* How to release a reference type : See clearly that the data of reference type has several variables that reference , It will not be released until it is released
Suggest : The code should be encapsulated in a function , The variables in the function will be released automatically
The index array : Subscripts are arrays of numbers
8、* relation (hash) Array :
What is? : Subscripts can be customized
Why? : The subscript of the index array has no specific meaning , Not easy to find
How to use :
1、 establish :2 Step
1、 Create an empty array :var arr=[];
2、 Add subscripts to the array and add elements :arr[" Custom subscript "]= The new value ;
2、 Access elements :arr[" Custom subscript "]
3、 emphasize :hash Array length Forever invalid , For ever 0!
Traverse hash Array , Out of commission for loop , You have to use for in loop - Designed to traverse arrays
for(var i in arr){
i;//
}
for in Although we can't define where to start , Where to end , Designed to traverse arrays , You can traverse both the index array and hash Array
Personal recommendations : Indexed arrays are still used for,hash Array in use for in
4、***hash The principle of arrays :
hash Algorithm : The string , Work out a number that does not repeat as much as possible ( Address values )
String content is the same , Then the calculated number must be the same
Additive elements : Give the custom subscript to hash Algorithm , Get a number ( Address values ), Put the data you want to save directly into this address
Get elements : Give the specified custom subscript to hash Algorithm , Get the same number as when you saved it ( Address values ), Find the currently saved data through the address
5、js Everything inside is an object , except undefined and null, The bottom layer of all objects is hash Array
3、***** Array of API: The predecessors defined it in advance , We programmers can use it directly , These functions are available only in arrays
1、*arr to string:
var str=arr.join(" Custom connector ");
Fixed routine :2 individual
1、 Pen test : Splice the contents of the array into one sentence / word ;
seamless splicing :var str=arr.join("");
2、 Splice the array into DOM Page elements
// data
var arr=[" Beijing "," nanjing "," Xijing "," Tokyo "," Chongqing "]
// To string , And splice the label
var str="< Start >"+arr.join("</ end >< Start >")+"</ end >";
// Render to DOM on the tree
elem.innerHTML=str;
2、* Array splicing : A new way to add elements
Splice all the arguments you pass in arr At the end of ,
var newArr=arr.concat( The new value 1,...)
special :1、 Do not modify the original array , Only a new array will be returned
2、concat Support passing in array parameters , Quietly break the array you passed in into single elements and then splice
3、* Truncation subarray :
Intercept the ending subscript according to the starting subscript you pass in
var subArr=arr.slice(starti,endi+1);
special :1、 Do not modify the original array , Only a new subarray will be returned
2、 With head and no tail
3、endi You can omit it , From starti The position is intercepted to the end
4、 In fact, both arguments can be omitted - From beginning to end , Deep copy , And the previous pass by value ( Shallow copy ) Different , One modification will not affect the other
5、 Support negative number parameter ,-1 For the last one
The above API Will not modify the original array
------------------------------------------------------------------------------------------------------------------------------
Following API Will modify the original array
4、* Delete 、 Insert 、 Replace :arr.length-=n
Delete :var dels=arr.splice(starti,n);//n Represents the number of deleted
special : Actually splice There are also return values , Returns a new array of elements you deleted
Insert :arr.splice(starti,0, value 1,...);
Be careful :1、 primary starti The element of position and subsequent elements will move backward
2、 Never insert an array , It will cause some of our arrays to be one-dimensional , Some are two-dimensional , Traversal is very uncomfortable
Replace :var dels=arr.splice(starti,n, value 1,...);
Be careful : The number of elements deleted need not be the same as the number of elements inserted
5、 Flip array :arr.reverse(); - I won't use it in the future
Expand : To answer a question in the interview in the future, press 4 Answer in three aspects (wwwh:what,when,why,how)
1、*****Array API:
1、***** Sort :2 Ways of planting
1、 interview / despise : Handwritten bubble sort : Let's start with the first element , Compare the two adjacent elements in turn , Just the previous element > The latter element , The two exchange positions
The formula :
for(var j=1;j<arr.length;j++){
for(var i=0;i<arr.length-j;i++){
if(arr[i]>arr[i+1]){
var middle=arr[i];
arr[i]=arr[i+1];
arr[i+1]=middle;
}
}
}
2、 Under formal development : Sort of API
arr.sort();
problem 1: By default, the elements will be converted into strings , Bitwise PK ascii code , If you want to sort by numbers ?
solve :
arr.sort(function(a,b){// Callback function
// console.log(a);// Get the last one
// console.log(b);// Get the previous one
return a-b;// If return The return is a positive number , Explain the last number > The previous number
// If return The return is a negative number , Explain the last number < The previous number
// If return Return is a 0, Explain the last number == The previous number
// And ours sort Method can be based on the positive number you return / negative /0 To sort
});
problem 2: Only in ascending order , How to descending
arr.sort(function(a,b){
return b-a;
})
emphasize : Sorting is actually very important , Bear in mind , As long as there is sorting function in the future pages , His bottom layer must be an array , Because only arrays have sorting methods
2、* Stacks and queues : New methods for adding and deleting elements
Start with :arr.unshift( The new value ,...);// A new way to add elements , Add forward , defects : Cause the subscript of other elements to change
Start out :var first=arr.shift();// A new way to delete elements , Forward deletion , defects : Cause the subscript of other elements to change
End in :arr.push( The new value ,...);// A new way to add elements , Add back , It's completely equivalent to arr[arr.length] perhaps arr.concat
End out :var last=arr.pop();// A new way to delete elements , Backward deletion
queue : It's just an array , It's just one end , At the other end
when : According to the order of first come first served , In reality, there are many
Start with :arr.unshift( The new value ,...);
End out :var last=arr.pop();
* End in :arr.push( The new value ,...);
Start out :var first=arr.shift();
ES3 Array of API Even after learning , Back ES5 It also provides 6 individual API Waiting for us to learn
2、 Two dimensional array : Elements of array , It also refers to another array
when : In an array , Hope to subdivide each category again
establish :
var arr=[
[" Zhang Sanfeng ",128,5500],
[" Zhang Cuishan ",38,4500],
[" zhang wuji ",18,12000]
];
visit :arr[ Line subscript ][ The following table ];
special : Column subscript out of bounds , return undefined
Row subscript out of bounds , Report errors , because undefined Out of commission []
Traversing a two-dimensional array : There must be a two-tier cycle : Outer loop control line , Inner loop control column
for(var r=0;r<arr.length;r++){
for(var c=0;c<arr[r].length;c++){
console.log(arr[r][c])
}
}
3、*****String The concept of :
What is a string : Composed of multiple characters 【 read-only 】 character 【 Array 】( read-only : Tomorrow we will learn all the strings API Will not modify the original string , Only new results will be returned )
1、*****String API: Functions that only strings can use , No need to create , Programmers use it directly
1、 Escape character :\
effect :1、 Convert the characters in the string that conflict with the program into the original
"\"" '\''
2、 Symbols containing special functions
Line break :\n
tabs :\t -> Big space tab
*3、 Output unicode Encoded character
\uXXXX: The first Chinese character :\u4e00 ascii:19968
The last Chinese character :\u9fa5 ascii:40869
2、* toggle case : Turn each English letter in the string into uppercase or A lowercase letter .
when : As long as the program is not case sensitive , Will be 【 First, unify 】 Capitalize or A lowercase letter , Compare again ( Verification Code )
how :
Capitalization :var upper=str.toUpperCase();
A lowercase letter :var lower=str.toLowerCase();
3、 Gets the character at the specified position in the string :var newStr=str.charAt(i); === str[i]
4、 Get the character at the specified position in the string ASCII code :
var ascii=str.charCodeAt(i);
according to ascii Code back to the original :
var original text =String.fromCharCode(ascii);
5、*** Retrieve string : Check index : Get the subscript of the keyword
var i=str/arr.indexOf(" keyword ",starti);
from starti Position start , Find the right side 【 First keyword 】 The location of
starti It can be omitted , The default from the 0 Location start search
Return value : find , What is returned is the subscript of the first character of the first keyword
* Did not find , return -1, Don't care about the subscript , Only care about for not for -1
effect : Judge whether there is
emphasize : Arrays can also be used in this way , Added later
Disdain the question : By default, you can only get the subscript of the first keyword , How to get the subscripts of all keywords ?
var str="no zuo no die no can no bibi";
var index=-1;
while((index=str.indexOf("no",index+1))!=-1){
console.log(index);
}
6、* Intercepting string :
var subStr=*str/arr.slice(starti,endi+1);// Same as array , Support negative number parameter ,-n It's for the last n individual
str.substring(starti,endi+1);// The usage is almost the same as slice identical , Negative parameter... Is not supported
*str.substr(starti,n);// Support negative number parameter ,n Represents the number of intercepts , There is no need to consider including head and tail
7、 String concatenation :var newStr=str.concat(str1,...);// Not so good + operation
8、* Replace string : The method itself is very powerful , But because we don't know regular expressions yet , Only fixed keywords can be replaced ( Next Monday )
var newStr=str.replace(" keyword "/ Regular ," New content ");
9、***** cutting / Split string :
effect : Convert string to array
var arr=str.split(" Custom cutter ");
special :1、 After cutting , The cutter does not exist
2、 A cutting charm "", Scatter every character
Expand :1、JS Create an empty element :
var elem=document.createElement(" Tag name ");
2、 Add the necessary attributes or events for this empty tag
elem.innerHTML=" Content "
elem. Property name =" Property value "
elem.on Event name =function(){}
3、 Render to DOM on the tree :
Parent element .appendChild( The new element )
边栏推荐
- Golang — template
- Sequence table (implemented in C language)
- mysql中的字段问题
- Leetcode-1175. Prime Arrangements
- Using registered classes to realize specific type matching function template
- [bw16 application] instructions for firmware burning of Anxin Ke bw16 module and development board update
- C language standard IO function sorting
- Which securities company has the lowest Commission for opening an account online? I want to open an account. Is it safe for the online account manager to open an account
- 8 Queen question
- 又一个行业被中国芯片打破空白,难怪美国模拟芯片龙头降价抛售了
猜你喜欢
When updating mysql, the condition is a query
从零开始的基于百度大脑EasyData的多人协同数据标注
SQL Injection (POST/Search)
Using registered classes to realize specific type matching function template
Implementation of Muduo accept connection, disconnection and sending data
Qt学习23 布局管理器(二)
SQL Injection (GET/Select)
Go language unit test 3: go language uses gocovey library to do unit test
GoLand 2021.1: rename the go project
Common network state detection and analysis tools
随机推荐
Complete DNN deep neural network CNN training with tensorflow to complete image recognition cases
MySQL 数据处理值增删改
JSON serialization case summary
[understanding by chance-37]: the structure of human sensory system determines that human beings are self-centered
Uniapp tips - scrolling components
Spring cup eight school league
Golang — 命令行工具cobra
JS general form submission 1-onsubmit
Go language web development series 28: solve cross domain access of CORS with gin contrib / CORS
3D vision - 2 Introduction to pose estimation - openpose includes installation, compilation and use (single frame, real-time video)
[how to solve FAT32 when the computer is inserted into the U disk or the memory card display cannot be formatted]
Replace the GPU card number when pytorch loads the historical model, map_ Location settings
Halcon combined with C # to detect surface defects -- Halcon routine autobahn
[how to earn a million passive income]
[combinatorics] permutation and combination (examples of combinatorial number of multiple sets | three counting models | selection problem | combinatorial problem of multiple sets | nonnegative intege
Golang — template
Sequence table (implemented in C language)
Go language unit test 3: go language uses gocovey library to do unit test
【BW16 应用篇】安信可BW16模组与开发板更新固件烧录说明
Qt学习25 布局管理器(四)