The first stage: C/S (Client Server) -> B/S (Browser Server) Web page production technology stack: PhotoShop, HTML, CSS
The second stage: from static to dynamic, from the back end to the front end front-end development engineers separation of the back end background: complete data analysis and business logic writing (including API interface writing) front-end: web page making, JS interaction effect, data interaction and binding
Technology stack: JavaScript, AJAX (cross-domain techniques), jQuery…
Stage 3: From the front end to the full end (from the PC end to the mobile end) technology stack: H5, CSS3, responsive layout development, Zepto, Hybrid (Hybrid APP development), wechat applets…
The fourth stage: from the full end to the full stack full stack development: both the front and back end can be developed (strictly speaking, a language to complete the development of the front and back end) technology stack: NODE(based on JS programming language server-side program development), Express/Koa…
In order to cater for the development of front-end development, there are many frameworks for developing, maintaining and improving performance in JS: Vue, React, Angular, Webpack…
Looking forward to WEB4.0 era, VR/AR first year, the front-end needs Canvas/webGL…
Webkit (v8 engine) : most browsers gecko: Firefox trident: IE…
-Leonard: Developers write code according to the W3C, and browser developers develop a set of things that render the code into pages according to the W3C.
Browser kernel function: according to certain specifications, the code based on GPU(graphics card) to draw the corresponding graphics and pages
Why there is browser compatibility: 1. Some browsers will develop better features in advance, which will be included in the W3C specification later, but there will be some compatibility before inclusion 2. Various browser vendors, in order to highlight their own uniqueness, have implemented the W3C specification in other ways…
JavaScript JS: a lightweight client scripting language
- HTML+CSS is a markup language. Programming languages are logical and have their own programming ideas (OOP, procedural programming).
- object-oriented
- C++
- JAVA
- PHP
- C # (.net)
- JS
- .
- Process oriented
- C
-
At present, JS is not only a client language, based on NODE can do server-side programs, so JS is a full stack programming language
-
To learn JS, we learn several parts of it
- ECMAScript (ES) : the core syntax of JS
- The document object Model provides various apis (properties and methods) that allow JS to retrieve and manipulate HTML elements (DOM and elements) in a page.
- BOM: Browser Object Model, provides various apis to enable JS to operate the browser
ESMAScript is the syntax planning of JS. Variables, data types, syntax specifications, operation statements, design patterns, and so on in JS are specified by ES
Variable is not a specific value, but a container or pronoun used to store a specific value. Because the value stored in it can be changed, it is called a variable
Based on the ES syntax specification, there are the following ways to create variables in JS
- var (ES3)
- Function (ES3) creates a function (the function name is also a variable, but the value stored is of the function type)
- let (ES6)
- Const (ES6) creates a constant
- Import (ES6) Export required information based on ES6 module specifications
- Class (ES6) Creates classes based on ES6
/ syntax: * * * var/variable name = value * let [variable name] = const value * * function/variable name = value function () {} * * *... * /
var n = 13;
n = 15;
alert(n+10);//=> pop up 25
const m = 100;
m = 200;//=>Uncaught TypeError: Assignment to constant variable. A constant cannot be reassigned (a value stored in a constant cannot be modified, which is a variable)
Copy the code
Create variables and follow a few conventions when naming them
- Strictly case sensitive
- Follow the camel name: Use numbers, letters, underscores (_), or $(a number cannot start a name with a number), and combine the names into a full name based on English words (lowercase first word, uppercase first letter of every meaningful word).
- Keywords and reserved words cannot be used: those that have special meaning in JS are called keywords, and those that may become keywords in the future are called reserved words
var n=12; var N=13; //=> The two n variables are different var studentInfo/student_info / _studentInfo (those preceded by the underscore are public variables) /$studentInfo(Typically stores JQ elements)... Add/create/insert del (delete)/update/remove (rm) info/detaillog.Copy the code
Six: data value is a programming language to produce the material, JS contains the values of the following types
- Basic data types (value types)
- Digital number
- String string
- Boolean Boolean
- null
- undefined
- Reference data type
- Object the object
- Ordinary objects
- The array object
- Regular object
- The date object
- .
- Function is the function
- Object the object
- New to ES6 is a special type: Symbol, a unique value
Var n = 13; //=>0 -13 13.2 The number type has a special value NaN (not a number is not a valid number, but is of type number) var s =' '; / / = >"" '13' "{}"Var b = all strings that are enclosed in single or double quotation marks are strings that contain the characters in the current string (a string consists of zero to multiple characters)true; //=> Boolean types have only two valuestruetruefalseFalse [reference data type] var o = {name:'Southern Flying Goose Training',age:9}; Var ary = [12,23,34,45]; var ary = [12,23,34,45]; Var reg = /-? Var reg = /-? (\d|([1-9]\d+))(\.\d+)? /g; //=> a complete re made up of metacharacters // not empty re is a single line commentfunction fn(){} [Symbol] creates a unique value var a = Symbol('Southern goose');
var b = Symbol('Southern goose');
a==b =>false
Copy the code
Extension: how JS code is run and how it outputs results after it is run.
- Running code in a browser (browser kernel for rendering and parsing)
- Run on NODE (which is also a tool for rendering and parsing JS based on V8 engine)
[How to output results]
- Alert: output by pop-up in the browser (browser prompt box)
var num=12;
alert(num); //=>window.alert
var str='Southern goose'; alert(str); All output based on alert is converted to a string: the value (evaluated first if an expression) is converted to a string using the toString method, and alert(1+1) is printed. = >'2'
alert(true); = >'true'Alert ([12, 10]); = >'12,
alert({name:'xxx'}); = >'[object Object]'The result of toString is object object, why?Copy the code
- Confirm: Confirm: Alert: Confirm: Confirm: Alert: Cancel: Confirm: Confirm: Alert: Cancel: confirm
var flag = confirm('Sure you want to quit? ');
if(flag){
//=>flag:trueThe user hits ok}else{
//=>flag:falseThe user hits the cancel button}Copy the code
-
Prompt: Add input fields to confirm
-
Console. log: Output logs on the browser console (press F12(FN+F12) to open the browser console)
- Elements: The Elements and styles of the current page can be seen here, and you can adjust the style and structure of the page
- Console: the Console, which can be output in JS code via.log, or directly write JS code
- Sources: The source files for the current site are all here
- .
-
Console. dir: more detailed than log output (especially when output object data values)
-
Console. table: Outputs a JSON data as a table
-
. (Go back and extend more console output methods yourself)
Seven, detailed analysis of data types
- Number Number type NaN: not a number but it is the isNaN of number type: checks if the current value is not a significant number, returning true for a significant number and false for a significant number
//=> syntax: isNaN([value]) var num=12; isNaN(num); //-> Check whether the num variable stores a value that is not a valid numberfalse
isNaN('13') = >false
isNaN('Southern goose') = >true
isNaN(true) = >false
isNaN(false) = >false
isNaN(null) =>false
isNaN(undefined) =>true
isNaN({age:9}) =>trueIsNaN ([12, 10]) = >true
isNaN([12]) =>false
isNaN(/^$/) =>true
isNaN(function() {}) = >true1. First verify that the value currently being tested is numeric. If not, the browser will convert the value to numeric by default.'13') ->13
Number('13px'If any non-valid numeric character occurs in the current string, the result is NaN Number('13.5') ->13.5 can recognize decimal [Boolean to Number] Number(true) ->1
Number(false) ->0 [other] Number(null) ->0 Number(undefined) ->NaN - ToString (); toString(); toString(); toString(); toString()'[object Object]'->NaN [array] [12,23].tostring () ->'12, ->NaN
[12].toString() ->'12' ->12
[正则]
/^$/.toString() ->'/^$/' ->NaN
Number(' ') ->0
[].toString() ->' '= > isNaN ([]) :false2. The value currently detected is already numeric and is returned as a significant digitfalseNot returntrue(Only NaN is not a significant number in the numeric type; the rest are significant numbers)Copy the code
- parseInt / parseFloat
Equivalent to Number, also to convert a value of another type to a numeric type
The difference between Number and string conversion analysis
Number: Any non-valid numeric character occurs, resulting in NaN
ParseInt: parseInt the integer part of a string. ParseFloat parseFloat parseFloat parseInt the integer part of a string
parseInt('13.5 px.) =>13
parseFloat('13.5 px.The parseInt () = > 13.5'width: 13.5 px.) =>NaN looks for a valid numeric character starting with the leftmost character of the string and converts to a number, but as soon as it encounters an invalid numeric character, the search endsCopy the code
- The comparison of NaN
NaN NaN:falseNaN was not equal to anyone, including himselfCopy the code
Question: there is a variable num, the value of the store does not know, I want to check whether it is a significant number, the following scheme can be
if(Number(num)==NaN){
alert('num is not a significant number! '); } NaN is equal to no one, and the condition is never true (even if num is indeed not a significant number and the conversion does result in NaN, but NaN! = NaN)if(isNaN(num)){//=> check whether the number is a significant number.'num is not a significant number! ')}Copy the code
Boolean type
There are only two values: true/false
How do I convert other data types to Booleans?
- Boolean
- !
- !!!!!
Boolean(1) = >true
!'Southern Flying Goose Training'=> Convert other data types to Booleans first, then invert!!null= >Taking two inverts is the same thing as taking no inverts, so you're left with a Boolean typeCopy the code
Rule: In JS, only “0/NaN/ empty string /null/undefined” are converted to Boolean false, the rest are converted to true
null && undefined
Both mean empty or nothing
- Null: Indicates an empty object pointer
- Undefined: undefined
Null is usually not expected. This is usually done manually. We will assign it again later.
var num = null; //=>null is a manual assignment, indicating that I will change the value of the num variable later. num =12;
Copy the code
Undefined is usually not manually controlled, most of which is left blank by the browser (it may or may not be assigned)
var num; //=> The browser assigns the value of the variable to be undefined. It may or may not be assignedCopy the code
Liu Tianrui (BOY) girlfriend is null, his boyfriend is undefined
Object Indicates the data type of an object
Ordinary objects
- Wrapped in braces
- Consists of zero to multiple groups of attribute names and attribute values (key-value pairs)
Attribute is used to describe the current characteristics of the object, the attribute name is the current possession of the feature, the attribute value is the description of the feature (professional syntax, the attribute name is a key, the attribute value is a value, a set of attribute names and attribute values is a set of key-value pairs)
var obj = {
name:'Southern Flying Goose Training'.age:9
};
//=> Object operations: add, delete, change, and check key/value pairsProperty/object [property] [get] obj. Name obj['name'In general, object attribute names are in string format (attribute values are not fixed, any format can be used)'Chau Xiao Tian'; //=> The NAME attribute exists in the original object
obj.sex='male'; //=> There is no SEX in the original object. This is equivalent to adding a new attribute SEX to the current object
obj['age'] =28; Delete: This attribute no longer exists in the objectdelete obj['age']; False delete: Does not remove this property, but leaves the current property null obj.sex=null; ---- When fetching an attribute value, if the current object has the attribute name, it can get the value normally (even if it isnull), but without the property name, the result is obtainedundefined
obj['friends'] = >undefined
Copy the code
Consider:
var obj = {
name:'Southern Flying Goose Training'.age:9
};
var name = 'zhufeng';
obj.name =>'Southern Flying Goose Training'Get the value of NAME property obj['name'] = >'Southern Flying Goose Training'Obj [NAME] => where NAME is a variable, we want to obtain the property NAME is not called NAME, is the value stored by NAME'zhufeng' =>obj['zhufeng'] => Does not have this property, the property value isundefined
----
'name'And name? = >'name'Is a string value that represents itself => name is a variable that represents the value that it storesCopy the code
Attribute names in an object are not only in string format, but may also be in numeric format
var obj = {
name:'Southern Flying Goose Training'0:10 0}; obj[0] =>100 obj['0'] =>100 obj.0 =>Uncaught SyntaxError: Unexpected Number ---- When we store property names that are not strings or numbers, the browser will convert the value to a string (toString), and then store obj[{}]=300; => store the result after ({}).toString() as the property name of the object.'[object Object]']=300 obj[{}] ='[object Object]'Var oo = {a:12}; Var ary = [12, 10]; //=>12 and 23 are attribute values. By looking at the result, we see that the array object's property name is a number (we call the number property name the index of the current object) ary[0] ary['0'] ary.0 => errorCopy the code
JS judgment operation statement
If/else if/else
var num = - 6;
if(num>10){
num++; //=>num=num+1 Num +=1 accumulates 1
}else if(num>=0 && num<=10){
num--;
}else{
num+=2;
}
console.log(num);
Copy the code
As long as one condition is true, no matter whether there are other conditions, the judgment is not executed
var num = 10;
if(num>5){
num+=2;
}else if(num>8){
num+=3;
}else{
num+=4;
}
console.log(num); / / = > 12
Copy the code
What can I write about conditions?
// >= / <= / == general comparison
if(0) {//=> Whatever you write in a conditional, always evaluate it to TRUE/FALSE in the end to determine whether the condition is TRUE (convert all other types of value to Boolean, except 0/NaN/ "/null/undefined is FALSE, all others are TRUE)
}
if('3px'+3) {//=> In JS, + - * / % is a mathematical operation. If a non-numeric value is encountered during the operation, it will be converted to the Number type first, and then the operation will be performed
//=>+ string concatenation (string concatenation, not math concatenation)
'3px'+3= >'3px3'
}
if('3px'- 3) {'3px'- 3= >NaN
}
Copy the code
BAT interview questions:
var num = parseInt('width: 35.5 px.);
if(num==35.5){
alert(0);
}else if(num==35){
alert(1);
}else if(num==NaN){
alert(2);
}else if(typeof num=='number') {//=> First calculate typeof num
//=> Comparing
alert(3);//=>alert outputs '3' in string format
}else{
alert(4);
}
Copy the code
typeof
One of the ways to detect data types in JS is:
- instanceof
- constructor
- Object.prototype.toString.call()
Grammar:typeof[value] => Check the data type of valuetypeofThe result is a string containing the corresponding data type, for example:"number"/"string"/"boolen"/"undefined"/"object"/"function"
typeof null= >"object"becausenullRepresents the null object pointer (does not point to any memory space)typeofCheck for arrays/re/objects and return both"object"In this way, it is impossible to segment the target audience:console.log(typeof []);
//=>"object"
console.log(typeof typeof []);
//=>typeof "object"
//=>"string"
Copy the code
2. Ternary operators
Grammar: Conditions? 2. Something that is not valid to do; <=> is equivalent to a simple if/else judgment
var num=12;
if(num>10){
num++;
}else{
num--;
}
//=> Overwrite to the ternary operator
num>10? num++:num--;Copy the code
A special case
//=> If a part of the ternary operator does not need any processing, we use null/undeifned/void 0... Placeholder can
var num = 12;
num>10? num++:null;
//=> If more than one operation is required, we wrap it in parentheses and separate each operation statement with a comma
num=10;
num>=10? (num++,num*=10) :null;
Copy the code
To consider
var num = 12;
if(num>0) {if(num<10){
num++;
}else{ num--; }}else{
if(num==0){
num++;
num=num/10; }} overwrite to ternary operator!Copy the code
3, the switch case
JS in a way of judgment
var num = 12;
if(num==10){
num++;
}else if(num==5){
num--;
}else{
num=0;
}
//=> Change to switch case
switch(num){
case 10:
num++;
break;
case 5:
num--;
break;
default:
num=0;
}
//=>switch case applies to different operations on variables (or expressions, etc.) with different values.
Copy the code
Every case comparison in the switch case is done on the basis of “===” absolute equality
'10'= =10= >trueEquality comparison, if the left and right sides of the equality sign are of different types, first the same data type is converted, and then the comparison is performed. => In this case, the string is converted'10'Converted to a number and then compared'10'= = =10Absolute comparison: If two data types are different, they are not equal. It requires that both types and values are exactly the same. (In real projects, we should use absolute comparison more often to ensure code rigor.)Copy the code
The FOR loop
Function: To do something repeatedly according to a certain rule, then we need to use a loop to deal with
Gets the DOM element in the page
document.getElementById
The element object is retrieved from the element’s ID attribute value throughout the document
GetElementById is the method that gets the element, and document defines the scope of the element, which we call “context.”
var oBox = document.getElementById('box');
1.The element obtained with getElementById is the value of an object data type (which contains many built-in attributes)typeof oBox =>"object"
2.ClassName: stores a string representing the style of the current element. ClassName: stores the id value of the current element (string). InnerHTML: stores all the contents of the current element (including the HTML tag). Store all the text content of the current element (no element tag) onclick: an event attribute of the element, based on which you can bind the current element to the click event onmouseOver: mouseover event onmouseout: mouse away event style: Store all of the current elementInline styleValues (fetch and manipulate only inline styles written on tags, styles written in stylesheets, not based on this property)...Copy the code
[context].getElementsByTagName
Gets a collection of elements by their label name in the specified context
The context is what we specify
var boxList = oBox.getElementsByTagName('li');
1.The result is an HTMLCollection of elements. First, it is also an object data type. The structure is very similar to that of an array (number is the index, length is the length), but it is not an array.0Boxlist. length Retrieves the number of LI's in the set2.Each item in the collection stores a value that is, in turn, an element object (object data type, containing many built-in attributes, such as id/className...). boxList[1].style.color='red'; Change the text color of the second LI in the collectionCopy the code
function
In JS, a function is a method (a function body), based on the function is generally to achieve some function
var total=10;
total+=10;
total=total/2;
total=total.toFixed(2);//=> keep two digits behind the decimal point (the number is used by a method called toFixed to keep the number behind the decimal point). In subsequent code, we still want to implement the same operation (plus10Divided by the2), we need to rewrite the codevar total=10;
total+=10;
total=total/2;
total=total.toFixed(2); . This way will lead to a large number of redundant code in the page, but also reduce the efficiency of development, if we can achieve this function of the code "encapsulation", later need this function can be executed, so it is good!Copy the code
Function is born in order to achieve encapsulation: encapsulates the code to implement a function to a function, later want to realize this function, you just need to put the function performs, unnecessary repetitive code again, the * * low coupling and high cohesion (reduce redundant code in the page and improve code repeat usage) * *
function fn(){
var total=10;
total+=10;
total/=2;
total=total.toFixed(2);
console.log(total); } fn(); fn(); . We can execute the function as many times as we want ===== ES3 standard://=> Create a function
functionThe function name ([parameter]){function body: the JS code that implements the function}//=> Function executionThe function name (); ===== ES6 standard create arrow function:letFunction name (variable name)=([parameter]) = >{body} Function name ();let fn=(a)= >{
let total=10; . }; fn();Copy the code
Functions, as one of the reference data types, also operate according to the reference address. Let’s look at how functions work
function fn(){
var total=10;
total+=10;
total=total.toFixed(2);
console.log(total); } fn(); Create a function1.Functions are also reference types, and a new heap is created to store the code in the function body as "strings" (objects store key-value pairs into memory).2.At this point we print fn(remember not fn()) to represent the current function itself. If we execute fn(), this is executing the function, so parentheses are two different operations of different nature. The code string stored in the heap memory is converted into real JS code for top-down execution, so as to achieve the due function1.Function execution first forms a private scope (an environment for code execution, also a stack memory)2.A copy of the string previously stored in heap memory is made into real JS code, which is executed from top to bottom in the newly created scopeCopy the code
Arguments in a function
Parameters are the entrance of a function: when we encapsulate a function in a function and find some raw materials are uncertain, the user can pass them in when the function needs to be executed. At this time, we can provide the entrance and exit based on the mechanism of parameters
//=> The parameters are called parameters: entry, parameters are variables (n/m is the variable)
function sum(n,m){
//=>n and m correspond to two digits of and
var total = 0;
total = n + m;
console.log(total);
}
//=> The values passed by the function execution here are arguments: arguments are concrete data values
sum(10.20); //=>n=10 m=20
sum(10); //=>n=10 m=undefined
sum(); //=> both n and m are undefined
sum(10.20.30); //=>n=10 m=20 30 No parameters are received
Copy the code
The way to detect data types in JS
- Typeof Operator used to detect data types (common)
- Instanceof checks whether the current instance belongs to a class
- Constructor Finds the constructor of the current instance based on the constructor
- Object. The prototype. ToString. Call call toString method on the base class Object prototype, when method execution method of this set to to test values, returns the current value of the corresponding class information
console.log(Number(null)); / / 0
Null = = undefined: true
Null = = = undefined: false
Null &&undefined is not equal to any other value
NaN NaN = = NaN: false and who are not equal including myself = = = = = = = = = = = = = = = = = = = = = = = = = = = > need special memories
1= =true= >true
1= =false= >false
2= =true= >falseNot to be confused with the rules, here is thetrueInto digital1[] = =true:falseAll converted to numbers0= =1! [] = =true:false[] = =false:trueAll converted to numbers0= =0! [] = =false:trueTo be first! [], convert array to Boolean inverse =>false= >false= =false
Copy the code