Summary of javascript knowledge

Posted Jun 28, 202017 min read

JS code principle:high cohesion, weak coupling

  1. ecmascript is a language standard. The first version of the standard was released in 1997. JavaScript is an implementation of Netscape's ecmascript standard.
  2. js does not distinguish between integers and floating-point numbers, uniformly expressed by number, nan said not a number, when unable to calculate the result by nan.
  3. The string string is any text enclosed in single or double quotes, such as'abc', "abc".
  4. Boolean value boolean, Boolean value has only two values, true or false.
  5. &&AND,||or,! non.
  6. Differences in programming forms:object-oriented, process-oriented
  7. typeof:six data types:number string boolean undefined object function

typeof returns two objects of the object:null and {}

  1. Browser composition
    shell part
    Kernel part

    Rendering engine(html and css basic grammar recognition, grammar rules and rendering)
    js engine
    Other modules
    In 2008, Google released the latest browser chrome, which can directly convert js code into mechanical code for execution.

  2. js features

js is an interpreted language(browser reads a line and translates a line, php/python is also an interpreted language)
Advantages:cross-platform, single thread(asynchronous transfer of data:)

  1. js standard

The standard is made by ecma, so it is sometimes called ecmascript
Yan Shen two parts dom bom
js three major parts:ecmascript, dom, bom
js execution queue:single thread, interpreted language, asynchronous transmission

  1. The kernel and private prefix of mainstream browsers

    ie kernel:trident private prefix:-ms-

    chrome webkit/blink -webkit-

    firefox gecko -moz-

    opera presto -o-

    safari webkit -webkit-

  2. Front-end development requirements:Separation of structure(html), behavior(js), and style(css)

  3. js variables(only var declared, floating point type)

Variable naming rules:must start with English letters, underscores and $; variable names can contain English letters, underscores, $and numbers; special syntax(keywords) and reserved words cannot be used as variable names;

  1. Basic JS syntax

type of data:

Common data types:number string Boolean undefined object function

The only difference between the reference value and the original value is the form of assignment
Original value:number boolean(true is 1, false is 0) string(string) undefined(variable is not assigned) null(indicating placeholder, value is empty) belongs to object type
The storage place is different
The original value is stored in the stack
"Last Out"
The only fundamental difference between the reference value and the original value is the form of assignment.
The original value is immutable. A value has been written in a room and cannot be changed.

When deleting data, it does not delete the location of the data in the memory, but only makes the number of the data packet not correspond to the data. There is no way to find it, but it still exists in the memory. Can only be covered twice.

The assignment between the stack memory is a copy, which does not affect each other, and the defined value cannot be changed

var z = 10;
var x = z;
z = 20;
//The output x value is 10;
  Reference value:array object function data regexp
The reference value is stored in the heap
Reference value copy Reference value copy is the address
var arr = [1,2];
var arr1 = arr;
//The output value is 1 2 5

Basic syntax

A semicolon must be added at the end of a line; the program reads a line of code to identify the semicolon,(the function function for loop if does not need to be added after;(semicolon) function for loop if judgment statement)

There must be a space on either side of any symbol

There are two kinds of errors

Low-level errors:

Can not write Chinese characters, grammatical analysis error

The console will display as follows:

uncaught syntaxerror:
invalid or unexpected token:

js operator

0/0 = NaN, 0%0 = NaN

1%0 = NaN, -1%0 = NaN

1/0 = infinity infinity is number type

-1/0 = -infinity
+:numeric operations, string concatenation(implicit conversion is on both sides of the string);

Any data type plus string is equal to a string(implicit conversion +)


var rr = 3;
rr%= 4;
//The output value is 3

//Change the value of aa bb
var aa = 123;
var bb = 234;
var temp = aa;
aa = bb;
bb = temp;

Boolean:false and true
String comparison is the order of asc code

Logical Operators

&&(AND):(AND returns the current value if it is false)

First look at the result of converting the first expression into a Boolean value. If the result is true, then it will look at the result of converting the second expression into a Boolean value. Then if there are only two expressions, then you will see the second expression. Formula, you can return the value of the(second) expression.

var a = 1 && 2 + 2; The returned value is 4, because the first one is to see if the value of var a = 1 is true. In this example, it is true, then the result of the calculation after &&(the last value) is returned 4;

The returned result is false:undfined, null, NaN, "", 0, false.

var a = 0 && 2 + 2; The returned value is 0, because the first one is false, the first value is returned directly.

var a = undefined && 2 + 2; the return value is undefined.

&& Upgrade:Interrupt function, short-circuit statement:Check whether the statement has errors or can be executed.

data && function(data); if data returns false, it means that data data does not exist or is wrong.

||(or):(return the current value if it is true)

||or operator is often used to solve browser compatibility issues


The execution order of the for loop:

for(var i = 0; i <10; i ++)

  1. var i = 0;
  2. if(i <10){} condition judgment
  3. i ++
  4. if(i <10){}
  5. i ++
  6. if(i <10){}

Conditional statements

The direct statements of if and else must be mutually exclusive, and satisfying condition 1 must not satisfy the remaining conditions.

i++ uses i first, and then calculates i = i + 1;

Small exercises:

Calculate the power of 2 to n, n can be input, n is a natural number:

var n = parseint(window.prompt("input number"));
//First define an initial value of mul
var mul = 1;
for(i = 1;i <= n; i++);{
//2 to the nth power
//A power of 2 represents 1 times a 2
//The second power of 2 represents 1 times 2 and then 2
mul *= 2;

Calculate the factorial of n, n can be input

var n = parseint(window.prompt("input a number"));
var jiemul = 1;
for(var i = 1;i <= n; i ++)
jiemul *= i;
Enter a, b, c, three numbers, print the largest
//Because you want to input three numbers, you must write three parseints
var a = parseint(window.prompt("input a");
var b = parseint(window.prompt("input b");
var c = parseint(window.prompt("input c");
if(a> b){
if(a> c){
if(b> c){

Conditional statements

When entering the week, display work or rest

var date = window.prompt('input');
switch(date) {
    case "monday":
    case "tuesday":
    case "wednesday":
    case "thursday":
    case "friday":
    case "saturday":
    case "sunday":

typeof operator:

Can return 6 values:number string Boolean object undefined function
Display type conversion:

Number:Convert the input content into numbers

String:Convert the input content into a string:

var demo ="123.3";
var num = String(demo);
console.log(typeof(num) + ":" + num);

Implicit type conversion:

Comma operator:English,

For example:The return result of 1, 2 is the value after the comma is 2, always returns the value after the last comma

//Output true:implicit conversion
//Output false
//false is 0, true is 1

Type conversion

Display type conversion and implicit type conversion

number:Convert the variable value to a number, null can be converted to 0, true is 1, false is 0, but one is special, undefined is converted to a number type, and it will output:nan. It seems that it is not a number but also output nan, If it is "123abc", it is also converted to NaN and cannot be converted to a specific number.

parseint:Convert the content to an integer number, which is an integer. Enter 123.98, it will be rounded down directly, output 123, input "123abc" output "123", parseint has a unique function, starting from the digits and looking backwards, has been Seeing the non-digit digits cut off, the previous digit is returned.

parsefloat:parseint is very similar, the difference is that float is a floating point number is a decimal, if the input content is:"123.45abc", it will output 123.45, it also starts from the number of digits, and has been seeing non-digits except. The bit is cut off, the latter is truncated, and the previous value is returned.
string:convert the content to a string,

boolean:Convert the content to a Boolean value. Enter 0-0 null undefined nan false and the empty string "" will output false, and the rest will output true.

tostring:whoever you want to convert into a string. Tostring, there are two special, undefined and null can not use tostring this method.

Implicit type conversion:

isNaN()-->(Number is called):Take the variable and put it in number first, then compare the conversion result with nan. If it is NaN, print out true, if not, output false. This number It must be NaN to return true, for example isNaN('100'), obviously 100 is not NaN, then return false

++/--, +(positive)-(negative)(calling number)

-(Minus sign)*/%-- number(also called number)

+(Plus sign)(calling string):There is a special syntax, when there is a string(string) on both sides of the plus sign, string will be called to convert both into a string. For example:var num =(1 + '2'); The output is 12, because the + plus sign has converted 1 into the string "1", so the result is 12.

<> <= >=(convert to boolean):var num = 1> "2"; print false.

==! =(The call is also boolean):undefined == null; print true, undefine is the same as null, >= <0 will output false.

No type conversion occurs(the left and right sides are exactly the same(type and number) will be absolutely equal, except for NaN)
===:absolutely equal
! ==:Absolutely not equal

Note:typeof(a) returns the string "undefined", so the type of the result printed by typeof is string.

Small exercises:

Note here:NaN is not equal to NaN, but undefined == null;


  1. Definition:function function name() {} function name and variable name format is similar,

But the naming must conform to the principle of small camel peak:the first letter of the word is lowercase, and the first letter of the following word must be uppercase.

  1. Function composition form:

Function name, parameters(formal parameters, arguments), and return value. Indefinite parameters,

  1. The scope of the function:(the parameters in the function are equivalent to the variables already defined in the function)

Js(single-threaded, interpreted language) runs the trilogy:

Grammar analysis, pre-compilation, interpretation and execution

arguments.length represents the number of actual parameters, and function name.lenth represents the number of formal parameters.

js pre-compilation:

Function declaration overall improvement

Variable declaration promotion(note that only declaration promotion, not assignment promotion)

imply global:implies global variables,

Global object:window

window is the global domain:

var a = 123;

It is equivalent to declare var a first; then a = 123;


Window is equivalent to a warehouse and is an object with the same function as GO(global object).

Any global variable is a property of window

Pre-compilation:all declared global variables(note that local variables are not included) are all window properties.

window is the global,

Pre-compilation occurs just before the function is executed:

Pre-compilation steps:
The first step:create an AO(activation object) object. The execution context is the scope of understanding

Step 2:Find the formal parameter and variable declaration of the function, and use the variable declaration name and formal parameter as the AO object number attribute name, the value is undefined

Step 3:Unify the actual and formal parameter values

Step 4:Find the function declaration in the function body(defining a variable equal to the function is not a function declaration(var a = function(){}), the function declaration must have a function name), the value is assigned to the function body
When the pre-compiled declared variable or function is output, if it has its own AO value, it prints out the value of the AO it owns, the principle of proximity, and it is not necessary to print out the value of GO is the window.


[[scope]]; a collection that stores the runtime context

Scope chain:a collection of execution context objects stored in scope

Find Variables:Look down from the top of the scope chain in sequence.

One additional point:in which function to find a variable, take the top of the function's scope chain and look down in turn.


If the internal function is saved to the outside, it must generate a closure.

Disadvantages:closures will cause the original scope chain not to be released, causing memory leaks

Memory leak:The more memory is occupied, the less available memory is.

The role of closures

Implement public variables:function accumulators

Can do cache:storage structure

Can achieve encapsulation, privatization of attributes

Modular development to prevent pollution of global variables

Closures:closures are generated when internal functions are called externally, and only closures can be called externally and change the properties of internal functions

Add, delete and modify

Object creation method:

1, var obj = {} plainObject //Object direct quantity
2. Constructor creation method
1) Constructor new Object() Array() Number()
2) Customize The first letter of the constructor should be capitalized
The internal principle of the constructor(three-stage)
1. Implicitly add this = {} at the front of the function body
2. Execute = xxx;
3. Implicitly return this
Only objects have properties and methods. Objects include functions, arrays, and objects themselves.

var str = new String(ass)

Add a new in front of the function, which is a constructor

Undefined and null can not set properties

Original value numbers cannot have attributes and methods, but objects can have attributes and methods.

The original value cannot call properties and methods

Prototype:An attribute of a function object that defines the common ancestor of the object created by the constructor. The object generated by the constructor can inherit the properties and methods of the prototype. The prototype is also an object.

Constructor name. prototype. attribute = value.

Extract the public part and write it into the prototype to reduce the redundancy of the code,

object.prototype is the terminal of the prototype chain.

The principle of the prototype chain is similar to the prototype, and the addition, deletion, modification and inspection are also similar.

Modification:If the attribute has a reference value, it can be modified

Object.create can also create objects

Most objects will eventually inherit from Object.prototype, not all object inheritance will eventually come from this.

Prototypes are internal attributes defined by the system and cannot be added by yourself.

Only undefined and null without toString and prototype

toString:into a string form, there is no method itself, to wrap the class

Math:ceil:round up:

Math:floor:round down:

math:random(); generates an open interval random number from 0 to 1(0, 1)

toFixed(n):save n significant digits, the number of valid digits after the decimal point is n, if it is an integer, then two zeros after the decimal point

If two significant digits are reserved, the third digit after the decimal point will be 1.

_Note:call/apply:change this to _

The actual application in the enterprise is to borrow other people's functions to achieve their own functions

The difference between call and apply:apply can only pass in one argument, and must be an array

The purpose of call and apply is to change the direction of this

The difference between the two is that the parameter list is different.(Call needs to pass the actual parameters according to the number of formal parameters(that is, the number of actual parameters == the number of formal parameters), apply needs to pass an argument list)

Inherit the history of development.

Prototype chain
2. Borrow the constructor
3. Shared prototype
4. Holy Grail Mode


  1. During function pre-compilation, this points to -> window. Arguments are placed in AO during pre-compilation, and there is also this:window, var this = Object.create(funxtion.prototype);
  2. In the global scope:this --> window, that is, there is also this:window in GO.
  3. call/apply can change the this point when the function is running. The difference between the two is the different parameter list.
  4. obj.func(); this in func() points to obj(who calls this method, this in this method points to)

Manage variables to prevent global pollution, suitable for templated development
Class array:
Components:The attribute must be an index(number) attribute, must have a length attribute, it is best to add a push method,
Once an attribute has undergone var operations, the resulting attribute is called a non-configurable attribute.
Attributes added through var are called non-configurable and cannot be deleted

  1. Precompile this --> window

  2. Who calls this to whom

  3. call apply

  4. Global this --> window

  5. try catch

If an error occurs in the try, the subsequent code in the try will not be executed, and then the outside
When the code in try is wrong, the subsequent code can still be executed
Error message

evalError:The use of eval() is inconsistent with the definition

rangeError:numeric value out of bounds


referenceError:(use is not defined without declaration(variable, function))

syntaxError:syntax parsing error(Chinese characters appear in the code)

The browser is based on the new method of es3 + es5

"Use strict", added to the top of the code becomes es5

The solutions that conflict with es3 use es5

The strict mode of es5 cannot be used with

with will treat the object inside as the top of the scope chain of the body of code to be executed

with can change the scope chain, the object inside with is AO

with can simplify the code

es5 specifies that variables must be declared before assignment

The local this must be assigned, what is the assignment

The local this is empty when precompiled, unassigned will be undefined

es5 can not repeat attributes and parameters, but no error

Eval can execute strings as code


document object model(operation html)

Standard programming interface to html

The basic operation of dom:

Get the keyboard code:

document.onkeydown = function(e) {console.log(e.which)};

Select an element of the page and press the key above the keyboard

Keyboard operation:upper 38, right 39, lower 40, left 37, enter:13, space:32, delete:8

Execute the function immediately:

The for loop contains a function that does not know when to execute, and this function accesses the for loop variable, you must use the immediately execute function function to solve the problem that i is changed to the final value
Sublime follows the plugin:

emmet tutorial

First install package control

Then preferences ----> packsge control installation, after the installation is complete, open the input install package ----> Enter emmet installation ---> Enter jsprettify installation.

dom basic operation

document represents the entire document

View the node of the element:


document.getElementsByTagName(commonly used)


document.getElementByName Only part of the tag name can take effect(form, img, iframe) Basically not used

querySelector:basically not used, the selected elements are not real-time,

Traverse the tree nodes

parentNode -> parent node(the topmost parentNode is #document)
childNodes -> child nodes
firstChild -> first child node
lastChild -> last child node
nextSibling -> next sibling node
previousSibling -> previous sibling node

Type of node:
Element node(1), attribute node(2), text node(3), comment node(8),

Traversal based on traversing element node tree

parentElement -> returns the parent element node of the current element(ie incompatible)
children -> returns only the element child nodes of the current element(commonly used)
node.childElementCount === node.children.length the byte point of the current element node
firstElementChild -> returns the first element node(ie incompatible)
lastElementChild -> returns the last element node
The previous sibling element node:
Last sibling element node

Four attributes of the node:

nodeName:the tag name of the element, which means read-only in uppercase

nodeValue:the attribute of the text or comment node, can be read and written

nodeType:read-only, not writeable(any element has such an attribute)

attributes:combination of attribute nodes of element nodes(can be assigned and modified)
A method of nodes:Node.hasChildNodes() has no child nodes, representing a function method, so you must add parentheses

Array-like plus a splice:Array.prototype.splice is followed by an array
Document can be understood as a constructor, document represents the entire document

The relationship between the two is gradually inherited

document -> HTMLDocument - >Document.prototype

HTMLDocument.prototype {_proto_:Document}

There are two direct attributes on the document, one body and one head

document.documentElement ---> refers to html
Three components of JS

ecmascript dom bom

Based on the traversal of the element node tree, except for children, the compatibility is relatively poor

The constructor has a prototype

dom structure tree, a series of inheritance

Nearest inheritance

date object

var date = new Date()

date.getTime(), milliseconds from January 1, 1970

setInterval is very inaccurate, the timer is a method on the window

setTimeout is only executed once

View the size of the viewport

window.innerWidth/innerHeight(plus scroll bar width/height)
Not compatible with IE8 and below
In standard mode, any browser is compatible
Works in browsers in weird mode
Encapsulation compatibility method, return browser viewport size getViewportOffset()

View the position of an element

dom.offsetLeft, dom.offsetTop

For elements without a parent, return the coordinates of the relative document. For elements with positioned parents, returns the coordinates relative to the nearest positioned parent.(Whether it is left or margin-left is the distance.)

The default value of position:static


Returns the closest positioned parent, if not, returns body, body.offsetParent returns null

____The distance the scroll bar scrolls on the y-axis + browser window height = total height of the document
When:the distance the scroll bar scrolls on the y-axis + the height of the browser window = the total height of the document
Description:has scrolled to the bottom \__

View the size of the viewport

window.innerWidth/innerHeight(plus scroll bar width/height)
Not compatible with IE8 and below
In standard mode, any browser is compatible
Works in browsers in weird mode
Encapsulation compatibility method, return browser viewport size getViewportOffset()

Scripted css

Special:eg:float > cssFloat

Compound attributes must be disassembled

Query calculation style

window.getComputesStyle(elem, null);
var style = window.getComputedStyle(div, null);
        //The second parameter is null
        //select pseudo element
        //null can get pseudo elements

Select the pseudo element of after

Change pseudo-element


    var after = window.getComputedStyle(div,'after');`

The default value of positioning left and top is auto


Event-triggered processes and functions

How to bind event handlers

  1. ele.onxxx = function(event) {}

Compatibility is good, but an element can only be bound to a handler, attribute assignment will be overwritten
Basically equivalent to writing between HTML lines,

  1. ele.addEventListener(type event type, fn handler function, false);

Incompatible below IE9, you can bind multiple handlers for an event

  1. ele.attachEvent(on + type, fn);

Unique to IE, an event can also be bound to multiple handlers

Once the event occurs in a loop, we must consider whether there is a closure, we must use the immediate execution function

The operating environment of the event handler

  1. ele.onxxx = function(event) {}

The program this points to the dom element itself

  1. obj.addEventListener(type, fn, false);

The program this points to the dom element itself

  1. obj.attachEvent(on + type, fn);

Program this points to window
AddEvent(elem, type, handle); method encapsulating compatibility

Dismiss event handler

ele.onclick = false/ /null;
ele.removeEventListener(type, fn, false);
ele.detachEvent(on  + type, fn);

Note:If you bind an anonymous function, it cannot be released

Event bubbling:

Structurally(non-visually) nested elements, there will be the function of event bubbling, anxious for the same event, bubbling from the child element to the parent element(from bottom to top)

Event capture:

Structurally(non-visually) nested elements, there will be the function of event capture, anxious for the same event, from the child element to the child element(bottom down)

If bubbling and capturing exist at the same time:
Trigger sequence, capture first, then bubble

Focus(focus event), blur, change, submit, reset, select and other events do not bubble

Cancel bubbling:

W3C standard event.stopPropagation(); but does not support versions below ie9
IE unique event.cancelBubble = true;
Encapsulate the function to cancel bubbling stopBubble(event)

Block the default event:

Default events   form submission, a label jump, right-click menu, etc.
1.return false; events registered in the form of object properties only take effect(very good compatibility)
2.event.preventDefault(); W3C annotation, incompatible below IE9
3.event.returnValue = false; compatible with IE
The function cancelHandler(event) that encapsulates the default event;

Event source object:

var target = || event.srcElement`

Function:It is not necessary to loop all the binding events of all elements one by one. When there are new child elements, there is no need to rebind all events

Mouse events:click, mousedown, mousemove(mouse movement event), mouseup, contextmenu(right click to cancel the menu), mouseover, mouseout, mouseenter, mouseleave(the effect is the same) html5 is written enter and leave

Use buttons to distinguish mouse buttons, 0/1/2

onclick = onmousedown + onmouseup

Order:down, up, click

Use the button to determine whether the left mouse button is clicked

button == 0 means the left mouse button

button == 2 means right mouse button

The dom3 standard stipulates that click can only monitor the left button, not the right button, and only onmousedown and onmouseup can be monitored.

js loading timeline:

Execution order
1. Create a Document object and start parsing the web page. After parsing HTML elements and their text content, add Element objects and Text nodes to the document. This stage document.readyState ='loading'.
2. Encounter link external CSS, create thread to load, and continue to parse the document.
3. Encounter script external js, and without setting async, defer, browser load, and block, wait for js to load and execute the script, and then continue to parse the document.
4. Encounter script external js, and set async, defer, the browser creates a thread to load, and continue to parse the document.
For scripts with async attributes, they are executed immediately after the script is loaded.(Asynchronous use of document.write() is prohibited)
5. When encountering img, etc., first parse the DOM structure normally, then the browser loads src asynchronously, and continues to parse the document.
6. When the document analysis is complete, document.readyState ='interactive'.
7. After the document analysis is completed, all scripts with defer will be executed in order.(Note that it is different from async, but it is also prohibited to use document.write(), which has the function of eliminating document flow);
8. The document object triggers the DOMContentLoaded event, which also marks the transition of program execution from the synchronization script execution phase to the event-driven phase.
9. When all async scripts are loaded and executed, img, etc. are loaded, document.readyState ='complete', the window object triggers the load event.
10. From now on, user input, network events, etc. are handled in an asynchronous response.

js regular expression


Escape character \
Normally:a carriage return representative \r\n
The role of regular expressions:the best choice for matching special characters or characters with special collocation principles.
Regular expression creation method:
Three modifiers for regular expressions:
I ignore case
g global matching
m Multi-line matching(.
Regular expression methods:test and string above the method match, string. match(regular expression)

[Reference book]
( )

Regular expression exec() method: