JavaScript on the front end



JavaScript is a scripting language, which is mainly composed of the following three parts:

  • Core (ECMAScript)
  • Document object model (DOM)   Document object model (integrating JS, CSS, HTML)
  • Browser object model (BOM)

Note: ES6 refers to ECMAScript 6.

Introduction of JavaScript

//First, write code in the script tag
    JS code

//Second, introduce JS file directly

JavaScript language specification

//This is a single line comment
multiline comment 

//The ending symbol is semicolon;

JavaScript language foundation (compared with Python)

Variable declaration

1. JS variable name can use letters, numbers, ﹣ and$ Composition, also can not start with a number

2. Declare variables with VaR and let (let is only supported after ES6)

3. You cannot use keywords as variable names

4. Const is used to declare constant. Once declared, the value cannot be changed (new in ES6)

var userName='json'
let id='111'
const PI=3.14

Note: variable names are case sensitive

JS recommends hump style naming rules, such as username

pyton   Recommended_ Underline naming rules: such as user_ name

The differences between VaR and let are as follows

var   All declared variables are global variables, which are easily affected

let   Local variables are declared, so let can distinguish between global variables and local variables

JavaScript data type

JS, like python, has dynamic types

>var x;
>var x=1;
>var x='alex'

Number type

JS doesn’t distinguish between integer and floating-point, so it only uses number

var a=11
var b=11.11
typeof b

Type conversion

ParseInt ('111 ') // returns 111
Parsefloat ('11.11 ') // returns 11.11
ParseInt ('11sagljks') // returns 11. If it is a decimal string, it returns the integer part. For example, 11.11 returns 11
ParseInt ("aljgla") // returns Nan
//Conclusion: as long as the beginning of a number can be converted, otherwise it will report an error

String type (string)

js   Support single quotation mark, double quotation mark, but more than three quotation marks

Python supports quotation marks, double quotation marks and triple quotation marks

String splicing:

JS recommends direct splicing with +

python   Join is recommended for splicing

var a="json";
var a1='pytoh';
Var A2 = ''Hello' // not supported

//Template string
var aa=`
    my name is ${a1} , ${a2}world
//Return my name is pytoh, hello world // Note: ${} will automatically go to the front to find the value corresponding to the variable name in braces. If it cannot be found, an error will be reported.

Common methods of string

JS method explain python
.length Return length .len()
.trim() Remove blanks  strip()
.trimLeft() Remove left margin  lstrip()
.trimRight() Remove right margin  rstrip()
.charAt(n) Returns the nth character  
.concat(value,…) Splicing join ()
.indexOf(substring,start) Subsequence position  index()
.substring(from,to) Get subsequence according to index ] index value
.slice(start.end) section [] 
 .toLowerCase() a lowercase letter lower() 
 .toUpperCase() Capitalization upper() 
 .split(delimiter,limit) division  split()


















h1=" hell "
>"hell "

>" hell"







>(3) ["hell", "w", "ld"]


Note: when JS uses slicing, it uses slice () method

The difference between slice and substring

String.slice (start, stop) and string.substring (start, stop)

The similarities between them are as follows
If start equals end, an empty string is returned
If the stop parameter is omitted, the end of the string is taken
If a parameter exceeds the length of a string, the parameter is replaced with the length of the string

The characteristics of substirng() are as follows
If start > stop, start and stop will be exchanged
If the parameter is negative or not a number, it will be replaced by 0

The characteristics of silce are as follows
If start > stop, the two will not be exchanged
If start is less than 0, the cut starts from the character (including the character at the position) of the first ABS (start) from the end of the string
If stop is less than 0, the cut ends at the ABS (stop) character from the end of the string (excluding the position character)

Boolean value

JS Boolean values are lowercase. The first letter of Boolean value in Python is uppercase

JS Boolean value is false: empty string, Nan, 0, undefined, null

The difference between null and undefined

  • Null means that the value is empty. It is usually used when a variable needs to be specified or cleared
  • Undefined means that when a variable is declared but not initialized, the default value of the variable is undefined

Note: when the return value is not set, the function returns undefined


JS in all objects, such as: string, numerical value, array, function

JS also provides multiple built-in objects, such as string, data, array, etc

Object knowledge is a special data type with attributes and methods


JS array is similar to the list in Python

The common methods of array are as follows:

JS array method explain python
length The size of the array Len (list name)
push(ele) Appending element at the end  append()
pop() Delete and get tail elements  pop()
unshift(ele) Insert element in head Insert (0, element)
shift() The header removes the element and gets its value  del l[0]/remove(l[0])
slice(start,end) section  l[0:2]
reverse() reversal  reverse()
join(seq) Connect the array elements into a string, and put the connector in the join() parameter Join (), on the contrary, such as’ a ‘. Join (L1)
concat(val,…) Join array   +
sort() sort  sort()
forEach() Pass each element of the array to the callback function  
splice() Delete elements and add new elements to the array  
map() After each element of the array is processed by the function, a new array is returned  map()


















var l=[1,2,3]



>(4) [6, 1, 2, 5]

l. Shift() # delete head element
>(3) [1, 2, 5]

>(2) [1, 2]

>(3) [5, 2, 1]


var l2=["a","b","c"]
>(6) [1, 2, 5, "a", "b", "c"]

>(3) [1, 2, 5]


Example of foreach() method: there are at most three parameters. The first parameter is required. The second parameter is optional. It represents the index value of the current element. The third parameter is optional. It represents the array object to which the current element belongs


Instance of splice (index, howmany, Item1) method: it is also three parameters. The first parameter is required to indicate the starting position, and the second parameter is also required to indicate the number of deleted elements, which must be a number and also “0”. If this parameter is not set, it will be deleted from index to the last element of the array. The third parameter, optional, indicates the new element to be added to the array.



Example of map() method: parameter properties are consistent with foreach


//Arithmetic operator + - * /% + +--
var x=1;
var res1=x++;    // The result is 1, which is assigned before operation
var res2=++x;    // The result is 3, which is calculated first and then assigned

//Comparison operator > > = < =! = = = = = = = = = = = = = = = = = = = ===
1 = = 1 // the result is true. Weak equals, data type will be converted automatically
1 = = = "1" // the result is false. Strong equals, data type will not be converted automatically

//Logical operators 
Note: Python is and or not
         JS is & & |!
         In logic operation, data is returned instead of Boolean value
0 || 1
//Assignment operator = + = - = * =/+

Process control

//If else structure
If (condition) {code block} else {code block}

//If else if - esle structure
If (condition){
Code block
}else if{
Code block
Code block

//Switch structure:
    case 0:
    Code block
//Note: a break statement is usually added to the case clause, otherwise the program will continue to execute the following statements in the case

//For structure:
For (condition)
  Code block

//While structure:
while(条件){Code block}

//Ternary operation
The python ternary operator is var res = 1 if 1 > 2 else 3
JS ternary operator is var res = 1 > 3? 1:3


Function definition (with or without parameters)

//Python is def JS is functionfunction f (parameter 1,...){
  Code block
//Anonymous function
var sum=function(a,b){
    return a+b;

//Execute function immediately
    return a+b;

//Arrow function (ES6 only allowed)
var f=v =>v;   // The left side of the arrow is the parameter and the right side is the return value
//Equivalent to
var f=function(v){
    return v

var f=(arg1,arg2) => arg1+arg2;
var f=function(arg1,arg2){
    return arg1+arg2;

Note: the arguments parameter in the function is the stored parameter.

Function can only return one value. If you want to return multiple values, you can only return them in an array or object

Global and local variables of functions

Local variables:A variable declared inside a function is a local variable, which can only be accessed inside the function. After the function is executed, the variable will also be deleted

global variable: a variable declared outside the function, which will be deleted after the page is closed

Scope:It is as like as two peas for Python scoping.

First of all, find the variable inside the function, and then go to the outer function to find the outermost layer step by step.

custom object

The essence is a set of key pairs, similar to the dictionary in Python.

#The first way to create custom objects
var d={'user':'hell','passwd':123}
#The second way is to create custom objects
var d1=new Object()'alex';         
//Equivalent to
D1 = {ID ':'alex','password ': 123} // traverse the object content for (VaR I in D1) {console. Log (I, D1 [i]);}

Data object

var d1=new Date();
Var D2 = new date ("2020 / 9 / 20 21:03") // the parameter is a date string
Var D3 = new date (1000) // the parameter is Ms
Var D4 = new date (2020,9,20,21,3,1100) // the parameter is month, year, day, hour, minute, second, millisecond
//Date object method
var d=new Date()
Getdate() // get the date
Getday() // get week
Getmonth() // get month (0-11)
Getfullyear() // get the complete year
Getyear() // get the year
Gethours() // get hours
Getminutes() // get minutes
Getseconds() // get seconds
Getmilliseconds() // get milliseconds
Gettime() // returns the cumulative number of milliseconds (from 1970 / 1 / 1 midnight)

JSON object

Serialization and deserialization in Python

  • dumps   serialize
  • loads     Deserialization

Serialize, deserialize and deserialize in JS

  • JSON.stringify()       Equivalent to dumps     serialize
  • JSON.parse()           Equivalent to loads       Deserialization

Regexp object

In Python, the use of regularization requires the help of re module,

In JS, you need to create regular objects

//The first way to create regular objects
Let reg1 = new regexp ("regular statement")
let reg1 =new RegExp(^[a-zA-Z][a-zA-Z0-9]{5,11})
//The second kind
Let reg2 = / regular statement/
Let reg2 = / ^ [a-za-z] [a-za-z0-9] {5,11} // / the match starts with a letter and the length is 5 ~ 11

//Match the content and call the test method

//Global matching defects
let reg2 = /^[a-zA-Z][a-zA-Z0-9]{5,11}/ g
The global pattern has a lastindex attribute. The matching result is true. Yes, lastindex is the length of the string. The next matching will start from the end of the string. When the matching result is false, lastindex will be reset to 0 and match from the beginning.
Reg2. Test ('helloworld ') // at this time, lastindex is 10, starting from the letter D, so the result is false

//The second defect is that when test () does not transfer parameters, it will be transferred to undefined by default