JavaScript
JavaScript basics
- External import
js
documents: through<script src="main.js"></script>
- Key words
- Variable names are case sensitive
- Naming conventions
JavaScript data type
- String
(String)
- digital
(Number)
- Boolean value
(Boolean)
- Undefined
(Undefined)
//undefined有两种结果
//1、真的没定义
alert(typeof dada); //undefined
//2、定义了,但是没有放东西进去
var dada;
alert(dada); //undefined
undefined
, Which means undefined or only declared variables with no value
- Object
(Object)
js
The following objects are built in:
Object
It is the super class (base class) of all JS objects, all objects in JS are inherited from the Object objectArray
Array object defines array properties and methodsNumber
Digital objectBoolean
Boolean object Boolean value relatedError
Error object handler errorFunction
Function object defines function properties and methodsMath
Mathematical objectsDate
Date objectRegExp
Object regular expression object definition text matching and filtering rulesString
String object defines string attributes and methods
Arithmetic operation
var y = 3;
Forced conversion
- String to number
parseInt() parseFloat() isNaN()
- Number to string
toString()
Assignment operation
- Compound assignment operator
+= -= *= /= %=
Relational operations
- Relational operations:
> < <= >= != == === ==和=== !=和!==
“=”、“==”、“===”
What's the difference?
=
Is the assignment symbol==
Ignore whether the data type is equal===
Value and data type must be equal to judge as equal
logic operation
- Logical and
&&
- Logical OR
||
- Logical negation
!
- Compound logical expression
Ternary operation
条件运算符?:
三元运算符:(比较表达式)?结果1:结果2
Branch loop
Three major structures of program operation: sequence structure, selection structure, and loop structure
- Single branch selection:
if
statement - Double branch selection:
if-else
statement - Multi-branch statement:
if-else if-else
statement
switch
Grammatical format
switch(num){ //表达式
case 1:
//执行代码块1
break; //中断执行,跳出
...
default: //默认,其他都不是的情况下执行
//执行代码块
break;
}
//强调:break非常重要,如果不加break的话,程序会一直继续往下执行;
while
Syntax format:
while
The characteristics of the cycle: when you don’t know the specific number of executions, use the most appropriate
while(条件表达式){
//要重复执行的代码段 - 循环体
}
do-while
Syntax format:
do{
//循环体
}while(循环条件判断);
do-while
It executes the loop body first, and then checks the loop conditions.do-while
It can be guaranteed that the loop body will be executed at least once.- Other loops cannot guarantee that the loop will be executed at least once.
for
for(1循环变量初始化;2循环条件判断;4循环变量的修改){
3循环体
}
break和continue
break
Exit the loopcontinue
Skip this cycle and continue to the next cycle
Array
- Array definition
var arr = new Array();
var arr = [];
- Literal method definition
var arr = ["1","2"];
- Assign value to array
arr[0] = "1";
arr[1] = "2";
alert(arr[0]+","+arr[1]);
- Array index
arr[0]+","+arr[1]
- Array length
//语法
arr.length
//最后一个元素的索引
arr.length-1
Array method
indexOf
The array can be indexOf()
used to search for the position of a specified element, if not found, return-1
concat
concat()
The method connects the current array with another array and returns a new array
var newArr = arr1.concat(arr2,"dada");
push和pop
push()
Add several elements to the end of pop()
the array , then delete the last element of the array
arr.push("a","b");
console.log(arr);
arr.pop();
console.log(arr);
//空数组继续pop不会报错,而是返回undefined
unshift和shift
unshift()
Add several elements to the front of shift()
the array , then delete the first element of the array
arr.unshift("a","b");
arr.shift();
slice
slice()
Intercept some elements of the array, and then return a new array
console.log(arr.slice(0,3)); //从索引0开始,到索引3结束,但不包括3
console.log(arr.slice(3)); //从索引3开始到结束
If you don't
slice()
pass any parameters, all elements will be intercepted from beginning to end. Using this, you can easily copy a new array
sort
sort()
Can sort the current array
var arr = ["b","c","a"];
arr.sort();
arr;//["a","b","c"]
reverse
reverse()
Drop the elements of the entire array one by one
join
join()
Method connects each element of the array with the specified string
var arr = ["a","b","c"];
arr.join("-"); //"a-b-c"
splice
You can delete several elements from the specified index, and then add several elements from that position
Two-dimensional array
var arr = [[1,2,3],["a","b","c"],"dadaqianduan"];
var x = arr[1][1]; //b
String
- String attribute
length
-the length attribute of the string slice()
slice(start[,end]),start--开始索引 end--结束索引
substr()
substr(start[,length]),start:开始,取length个字符
split()
split([separator[,limit]])
,Split the string by condition and return the array
indexOf()
The position of the first appearance in the parent string, from the 0
beginning! Did not return-1
lastIndexOf()
Reverse search
charAt(index)
charAt(index)
Specify the character of the index
toLowerCase()
Lowercase
toUpperCase()
To uppercase
Regular expression
Create regular expression
var reg = new RegExp("a","i");
// 将匹配字母a,第二个参数i,表示匹配时不分大小写
复制代码
Metacharacter
Mode modifier
Regular method
test
method
Retrieve the value specified in the string.
exec
method
This method is used to retrieve the matching of the regular expression in the string . The function returns an array in which the matching results are stored. If no match is found, the return value is null
.
Support regular String method
js object
Define the object
//使用new运算符
var obj = new Object();
//字面量
var obj={
name:"dadaqianduan",
age:12,
sex:"男"
}
复制代码
Object data access
//用.语法
obj.name
//用[]语法
obj["name"]
JSON
json(JavaScript Object Notation)
, Is a lightweight data exchange format.
var man = {
"name":"dadaqianduan",
"age":12,
"sex":"男"
};
Built-in objects
Object
It is the super class (base class) of all JS objects, all objects in JS are inherited from the Object objectArray
Array objectNumber
Digital objectBoolean
Boolean objectError
Error objectFunction
Function objectMath
Mathematical objectsDate
Date objectRegExp
Regular expression objectString
String object
Math method
abs()
Absolute value (excluding positive and negative)random()
Random numbers, random numbers in0-1
between,1
will not appearround()
roundingfloor(x)
Round down (round down)ceil(x)
Floor ceiling (improvement adjustment)max(x,y)
x 和 y
The maximum value inmin(x,y)
x 和 y
The smallest value incos(x)
x
Cosinesin(x)
x
Sine ofsqrt(x)
x
Square root returnedpow(3,4)
Return3
of4
power
Date method
getFullYear()
Return year (4 digits)getMouth()
Return month (0–11)getDate()
Return dategetDay()
Return week (0-6)getHours()
Return hourgetMinutes()
Return minutesgetSeconds()
Return secondsgetTime()
Returns the number of milliseconds from midnight on January 1, 1970 to the specified date (string)setFullYear()
Set yearsetMouth()
Set monthsetDate()
Set daysetHours()
Set hoursetMinutes()
Set minutessetSeconds()
Set secondssetTime()
Set the time object in the form of milliseconds
//判断闰年
function runYear(year){
if(year%4==0 && year%100!=0 || year%400==0){
return true;
}
};
Object-oriented is a programming idea
- Class is an abstract concept
- Object: specific things
- A class is an abstraction of an object, and an object is a concrete instance of the class
- Classes do not occupy memory, objects occupy memory space
- Access declaration object
- Traverse objects-
for in
loop
Define the object
- Literal creation
- Factory mode
// 工厂模式中的函数,首字母大写
function Cat(n,c){
return {
name:n,
color:c,
say:function(){
alert("dadaqianduan")
}
}
}
- Constructor
Javascript
Provides a constructor(Constructor)
mode.
The so-called "constructor" is actually an ordinary function, but this
variables are used internally .
Using new
operators on the constructor will generate an instance, and the this
variables will be bound to the instance object.
Capitalize the first letter of the constructor
this
The instantiated object pointed to in the constructor
function Cat(n,c){
this.name=n;
this.color=c;
}
Generate instance objects
var cat1 = new Cat("dadaqianduan","黄色")
// 自动含有一个constructor属性,指向它们的构造函数
Example: automatically contains an
constructor
attribute, pointing to their constructor
alert(cat1.constructor == Cat); //true
Javascript
Aninstanceof
operator is also provided
Verify the relationship between prototype objects and instance objects.
var txt = 'dadaqianduan';
alert(txt instanceof String); //false
var age = 123123;
alert(age instanceof Number); //false
var res = /\d/;
alert(res instanceof RegExp); //true
var arr = [];
alert(arr instanceof Array); //true
Prototype and prototype chain
The constructor has an
prototype
attribute that points to another object. All properties and methods of this object will be inherited by the instance of the constructor.
All functions are Function
examples.
Attribute on a prototype have constructor prototype,prototype
is also an object; the object has a constructor
property that is directed constructor.
There is an _proto_
attribute on the instance object , which also points to the prototype object. This attribute is not a standard attribute and cannot be used in programming. This attribute is used internally by the browser.
constructor
constructor
It is the attribute of the instance created by the constructor. The function of this attribute is to point to the constructor of the current object.
son.constructor == parent; // true
Each prototype has an constructor
attribute that points to the associated constructor.
function Person() {
}
console.log(Person===Person.prototype.constructor) //true
relation chart:
Distinguish between ordinary objects and function objects
function f1(){};
var f2 = function(){};
var f3 = new function(){};
var o1 = {};
var o2 = new Object();
var o3 = new f1();
console.log(typeof Object); //function
console.log(typeof Function);//function
console.log(typeof f1) //function
console.log(typeof f2) // function
console.log(typeof f3) //function
console.log(typeof o1) //object
console.log(typeof o2) //object
console.log(typeof o3)// object
- In
JavaScript
, the prototype is an object, and the role of the prototype is to realize the inheritance of objects. - In
JavaScript
all the function objects in, there is an attributeprototype
, which corresponds to the prototype of the current object. - All
JavaScript
objects have an_proto_
attribute, which_proto_
points to the prototype of the constructor function of the instance object.
var p = new Person(); // 实例对象
console.log(p._proto_ === Person.prototype); // true
p
It is an instance object, itPerson
isp
a constructor.p
The_proto_
property points constructorPerson
prototype.
js
How to inherit through prototypes:
var parent = function(name) {
this.name = name;
}
parent.prototype.getName = function() {
return this.name;
}
var son = new parent("dadaqianduan");
console.log(son.getName()); // dadaqianduan
son
parent
Function attributes in inherited prototypesgetName
Prototype chain
Except
Object
forprototype
the prototypenull
, all objects and prototypes have their own prototype, and the prototype of the object points to the prototype object.
In a multi-level relationship, multiple prototypes are connected to form a prototype chain.
When looking up an object's property, if the current object can't find the property, it will look up along the prototype chain until it is found. If it reaches the top of the prototype chain and it is not found, it will returnundefined
prototype
- All reference types have an
__proto__
attribute - All functions have an
prototype
attribute - All
__proto__
attributes of a reference type point to its constructorprototype
The relationship between the constructor and the instance prototype:
Person
(Constructor) is prototype
directedPerson.prototype
__proto__
Each object, in addition to null
outside, have a property called __proto__
, this property will point to the prototype of the object.
function Person() {
}
var person = new Person();
console.log(person.__proto__ === Person.prototype); // true
relation chart:
relation chart:
relation chart:
Sorting out:
Write a constructor Person
. The difference between a general constructor and a normal function requires the first letter to be capitalized:
function Person(){}
prototype
prototype
A prototype is an object, and prototype
the properties defined on the prototype can also have this property through "inheritance".
Inheritance is the new
intra-operator implemented.
Internal constructor has a
prototype
property, you can access to the prototype by this property.
Person
Is the constructor, Person.prototype
is the prototype.
- Instance
There are constructors, you can create inheritable properties on the prototype, and new
create instances through operators:
function Person(){}
person = new Person()
da = person instanceof Person // 检查person是否是Person的实例
da // true
// 继承
function Person() {}
Person.prototype.name = 'dadaqianduan.cn'
person = new Person()
da = person.name // 实例继承的属性
da // 'dadaqianduan.cn'
proto
The instance is _proto_
accessed to the prototype.
function Person() {}
Person.prototype.name = 'dadaqianduan.cn'
person = new Person()
da = person.__proto__ === Person.prototype
da // true
constructor
Constructor
The prototype can also be
constructor
accessed through the constructor
function Person() {}
Person.prototype.name = 'dadaqianduan.cn'
person = new Person
da = Person.prototype.constructor === Person
da // true
summary
- All reference types (functions, arrays, objects) have
__proto__
properties. - All functions have
prototype
attributes. - Each instance object (
Object
) has a private property,__proto__
which is the prototype object (prototype
) that points to its constructor . The prototype object also has its own prototype object__proto__
, layer by layer until the prototype object of an object isnull
,null
there is no prototype, and it serves as the last link in the prototype chain.
Common JavaScript design patterns
Baidu Encyclopedia:
A design pattern (Design pattern)
is a set of code design experience that has been used repeatedly, is known to most people, and is catalogued.
The use of design patterns is to reusable code, make it easier for others to understand, and ensure code reliability. There is no doubt that design patterns are win-win for others and systems; design patterns make code preparation truly engineering; design patterns are the cornerstone of software engineering, just like the structure of a building.
Single mode
A monolith is an object used to divide the namespace and group related properties and methods together. If it can be instantiated, it can only be instantiated once.
Features:
(1) The namespace can be divided to eliminate the dangers caused by global variables.
(2) Use branch technology to encapsulate the differences between browsers.
(3) The code organization can be more integrated for easy reading and maintenance.
Factory mode
Definition of factory mode:
Providing an interface for creating objects means that the corresponding products (objects) are produced according to the instructions (parameters) of the leader (caller).
- Creating an object often requires a complicated process, so it is not suitable for a complex object.
- Creating objects may result in a lot of repetitive code, or it may not provide a sufficient level of abstraction.
The factory is to transfer the creation of member objects to an external object. The advantage is to eliminate the coupling between objects (that is, mutual influence).
classification:
Simple factory pattern : Use a class, usually a single unit, to generate instances.
Complex factory pattern definition : Push the actualization of its member objects to the subclass, and the subclass can override the parent class interface method to specify its own object type when it is created.
The parent class only deals with the general issues in the creation process. These treatments will be inherited by the subclasses, and the subclasses are independent of each other, and the specific business logic will be written in the subclass.
Application scenarios:
The factory model is particularly useful in the following scenarios:
(1) The construction of the object is very complicated;
(2) Need to rely on specific environments to create different instances;
(3) Dealing with a large number of small objects with the same attributes.
Singleton mode
The singleton mode defines the creation process of an object, this object has only a single instance, and provides a global access point to access it. It can also be said that a singleton is to ensure that there is only one instance of a class. The method of implementation is generally to first determine whether the instance exists or not, if it exists, return directly, if it does not exist, create it and return again, which ensures that a class has only one instance object.
Use closures to implement singletons:
var single = (function(){
var unique;
function getInstance(){
// 如果该实例存在,则直接返回,否则就对其实例化
if( unique === undefined ){
unique = new Construct();
}
return unique;
}
function Construct(){
// ... 生成单例的构造函数的代码
}
return {
getInstance : getInstance
}
})();
unique
Return references to objects, andgetInstance
static methods to obtain instances.Construct
Is the constructor to create an instance.
Can single.getInstance()
be obtained a single embodiment, and each call are obtained with a single embodiment . This is the singleton pattern effect achieved.
Application scenarios:
- Singleton mode is a commonly used mode. We often only need one object for some objects, such as global cache and browser
window
objects. - With the help of singleton mode, the code organization can be more consistent, which is easier to read and maintain.
This article is serialized, so stay tuned~
The front-end interview questions I want to share below are the questions I encountered during the interview. I will review and summarize after each interview. I did a sorting, and found a professional answer in the technical blog, divided into HTML, css, JavaScript, React, Vue, browser, server and network, algorithm, etc... You can refer to the following: