Jack N @ GitHub

Full stack engineer, focus on: Angular/React, node.js/.Net

0%

前端进阶(2)使用fetch/axios时, 如何取消http请求

1. 需求

现在前端都是SPA,我们什么时候需要取消HTTP请求呢?

  1. 当我们从一个页面跳转到另外一个页面时,如果前一个页面的请求还没有返回,那么我们希望取消前一个页面的请求
  2. 某些操作耗时比较长(不能是保存等操作哦),如果用户不想等待呢,取消了操作,对应我们也需要取消HTTP请求

对于原生的XMLHttpRequest,是支持取消http请求(abort)操作的: XMLHttpRequest.abort()
那么,当我们使用ES6的fetch,或者使用axios库,如何实现呢?

2. Fetch 取消http请求

fetch与XMLHttpRequest(XHR)类似,是ES6之后浏览器(除IE之外)默认支持的http操作函数。可惜不是默认支持abort操作。但我们可以通过AbortController来实现, 直接上代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 声明AbortController
const controller = new AbortController();

// 正常的http调用
fetch('https://jackniu81.github.io', { signal: controller.signal })
.then(r => r.json())
.then(response => {
console.log(response);
})
.catch(err => {
if (err.name === 'AbortError') {
console.log('Fetch was aborted')
} else {
console.log('Error', err)
}
});

// 需要取消请求时,调用:
controller.abort()

3. axios取消http请求

axios 已经实现了abort操作,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var source = axios.CancelToken.source();

axios.get('https://jackniu81.github.io', {
cancelToken: source.token
}).catch(function(err) {
if (axios.isCancel(err)) {
// handle our cancel operation
console.log('Request canceled', err.message);
} else {
// handle real error here
}
});

// 需要取消请求时,调用:
source.cancel('Abort Request');

4. jquery 取消http请求

$.ajax内部已经实现了abort功能。直接调用.abort()即可。

5. 总结

  1. fetchAbortController集成:我们将signal属性作为可选参数(option)进行传递,之后 fetch 会监听它,因此它能够中止 fetch.
  2. AbortController 是可伸缩的,可以用于一次性终止多个请求
  3. 参考fetch的实现,我们自己的代码也完善一下,实现基于AbortController操作取消操作;
  4. axios 默认支持Abort操作;

前端进阶(1)Web前端性能优化

Web前端性能优化, 不仅能够改善站点的用户体验,并且能够节省相当的资源利用。下面将从1)服务器、2)html内容、3)css、 4)javascript、 5)图片等几方面介绍具体的优化操作。

目录:

1. 服务器优化

1.1. 使用内容分发网络(CDN)

把网站内容分散到多个、处于不同地域位置的服务器上可以加快下载速度。

1.2. 服务器使用http2.0协议

Http2.0的优点

  1. 二进制分帧
  2. 首部压缩
  3. 流量控制
  4. 多路复用
  5. 请求优先级
  6. 服务器推送

e.g 使用nginx, 要求 1)v1.9.5以上, 2)使用https;

1.3. GZIP压缩

1.4. 使用浏览器缓存

CSS、javascript、logo、图标这些静态资源文件更新的频率都比较低,而这些文件又几乎是每次http请求都需要的,如果将这些文件缓存在浏览器中,可以极好的改善性能。

通过设置http头中的cache-controlexpires的属性,可设定浏览器缓存,减少网络请求次数。

1.5. 设置ETag

ETags(Entity tags,实体标签)是web服务器和浏览器用于判断浏览器缓存中的内容和服务器中的原始内容是否匹配的一种机制。

2. HTML内容优化

2.1. 减少HTTP请求数

这条策略是最重要最有效的,因为一个完整的请求要经过DNS寻址,与服务器建立连接,发送数据,等待服务器响应,接收数据这样一个消耗时间成本和资源成本的复杂的过程。 常见方法:

  1. 合并多个CSS文件和js文件, 并进行最小化处理。
  2. 利用CSS Sprites整合图像,
  3. 行内图片Base64编码,使用 data:URL scheme在实际的页面嵌入图像数据
  4. 合理设置HTTP缓存

2.2. 减少DNS查找

为了减少DNS的询次数,最好的解决方法就是在页面中减少不同的域名请求的机会。

2.3. 避免重定向 301/30x

如果重定向的话,就需要在访问过程中重复发起一连串的动作,会消耗很多时间,因此避免出现多次重定向地址或资源的访问。

2.4. 避免在html标签中写style属性

js,css 写到单独的文件中,便于浏览器缓存。

2.5. 异步加载组件,预加载组件 (ansyc, defer)

ansyc, defer不会阻塞浏览器的文档解析。

  1. ansyc用于异步加载
  2. defer用于预加载

    2.6. 延迟、分页加载图片

    对于图片而言,在页面刚加载的时候可以只加载第一屏,当用户继续往后滚屏的时候才加载后续的图片。这样一来,假如用户只对第一屏的内容感兴趣时,那剩余的图片请求就都节省了。

2.7. 减少DOM元素数量

页面中存在大量DOM元素,会导致javascript遍历DOM的效率变慢。

2.8. 最小化iframe的数量

iframes 提供了一个简单的方式把一个网站的内容嵌入到另一个网站中。但其创建速度比其他包括JavaScript和CSS的DOM元素的创建慢了1-2个数量级。

2.9. 避免404

HTTP请求时间消耗是很大的,因此使用HTTP请求来获得一个没有用处的响应(例如404没有找到页面)是完全没有必要的,它只会降低用户体验而不会有一点好处。

2.10. 对Ajax请求使用GET方法

2.11. 避免空的图像src

3. CSS优化

3.1. 将CSS代码放在HTML页面的顶部

3.2. 合并、压缩CSS

3.3. CSS选择符优化

  1. 浏览器对选择符的解析是从右往左进行的
  2. 按照ID查询效率最高

3.4. 避免使用CSS表达式

3.5. 使用来代替@import

3.6. 避免使用Filters

4. javascript优化

4.1. 将JavaScript脚本放在页面的底部

4.2. 将JavaScript和CSS作为外部文件来引用

在实际应用中使用外部文件可以提高页面速度,因为JavaScript和CSS文件都能在浏览器中产生缓存。

4.3. 合并、压缩JavaScript

4.4. 删除无用、重复的脚本

4.5. 最小化DOM的访问

使用JavaScript访问DOM元素比较慢

4.6. 开发智能的事件处理程序

4.7. javascript代码注意

  1. 减少作用域链查找(多用局部变量,少访问全局变量)
  2. 减少闭包的使用,避免内存泄漏
  3. 谨慎使用with
  4. 避免使用eval Function函数
  5. 字符串拼接, Javascript中使用”+” 号来拼接字符串效率是比较低,建议使用数组的 join方法

5. 图像优化

5.1. 优化图片大小

5.2. 通过CSS Sprites优化图片

5.3. 不要在HTML中使用缩放图片

5.4. favicon.ico要小而且可缓存

6. 其他

6.1. 减小Cookie大小,尽量不使用cookie

cookie包含在每次请求和响应中,太大的cookie会严重影响数据传输

6.2. 负载均衡

负载均衡load balancer,降低每个站点的请求书,提高单个请求的响应时间。

https://jackniu81.github.io/2021/04/22/2021-Top-100-C-NET-Interview-Questions-And-Answers/

1. What is the difference between “dispose” and “finalize” variables in C#?

  1. Dispose - This method uses interface – “IDisposable” interface and it will free up both managed and unmanaged codes like – database connection, files etc.
  2. Finalize - This method is called internally unlike Dispose method which is called explicitly. It is called by garbage collector and can’t be called from the code.

2. What does “Jagged Arrays” mean?

Answer: Jagged arrays refer to the array that has an element of type array. The dimensions and the sizes of the elements are different. An array of arrays is the other name of the jagged array.

3. What is a Class and an Object?

A ‘Class’ is an encapsulation of methods and properties that are used to represent an entity in real-time. Class brings all of the instances together in a single unit. An ‘Object’ is an instance of a Class, or a block of allocated memory that can be stored in the form of Variables, Array or a Collection.

4. Explain Code compilation in C#

Code compilation has four steps which include:

  1. Compiling source code to Managed code by C# compiler
  2. Executing the assembly by CLR
  3. Combining the new code into assemblies
  4. Loading the Common Language Runtime (CLR)

5. What is the difference between Virtual method and Abstract method?

A Virtual method must always have a default implementation. An Abstract method does not have an implementation. An override keyword is not necessary here, though it can be used.

6. What is a Hashtable in C#?

A Hashtable is a collection that stores (Keys, Values) pairs. Here, the Keys are used to find the storage location and is immutable and cannot have duplicate entries in a Hashtable. The .Net Framework has provided a Hash Table class that contains all the functionality required to implement a hash table without any additional development. The hash table is a general-purpose dictionary collection. Each item within the collection is a DictionaryEntry object with two properties: a key object and a value object. These are known as Key/Value. When items are added to a hash table, a hash code is generated automatically. This code is hidden from the developer. Access to the table’s values is achieved using the key object for identification. As the items in the collection are sorted according to the hidden hash code, the items should be considered to be randomly ordered.

7. What is LINQ in C#?

LINQ stands for Language Integrated Query. LINQ is a data querying methodology that provides querying capabilities to .NET languages with a syntax similar to a SQL query.

LINQ has a great power of querying on any source of data. The data source could be collections of objects, database or XML files. We can easily retrieve data from any object that implements the IEnumerable interface.

Advantages of LINQ

  • LINQ offers an object-based, language-integrated way to query over data no matter where that data came from. So through LINQ, we can query a database and XML as well as collections.
  • Compile-time syntax checking.

8. What are Indexers in C#?

C# introduces a new concept known as Indexers which are used for treating an object as an array. The indexers are usually known as smart arrays in C#. They are not an essential part of object-oriented programming.

Defining an indexer allows you to create classes that act as virtual arrays. Instances of that class can be accessed using the [] array access operator.

9. Difference between the Equality Operator (==) and Equals() Method in C#

Both the == Operator and the Equals() method are used to compare two value type data items or reference type data items. The Equality Operator (==) is the comparison operator and the Equals() method compares the contents of a string. The == Operator compares the reference identity while the Equals() method compares only contents.

10. What’s the Difference between the Is and As operator in C#

  • “is” operator: In C# language, we use the “is” operator to check the object type. If two objects are of the same type, it returns true, else it returns false.

  • “as” operator: The “as” operator behaves in a similar way as the “is” operator. The only difference is it returns the object if both are compatible with that type. Else it returns a null.

11. What are Different Ways a Method can be Overloaded?

Method overloading is a way to achieve compile-time polymorphism where we can use a method with the same name but different signatures. For example, the following code example has a method volume with three different signatures based on the number and type of parameters and return values.

12. What is Serialization?

Serialization converts a code to its binary format using a process. After it is converted to bytes, it can be easily stored and written to a disk. Serializations are useful so that the original form of the code isn’t lost and it can be retrieved later on.

13. What are the different types of Delegates?

The different types of Delegates are: Single Delegate, Multicast Delegate and Generic Delegate.

14. How to use extension methods?

An extension method is a static method of a static class, where the “this” modifier is applied to the first parameter. The type of the first parameter will be the type that is extended.

Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive.

15. What is the difference between String and StringBuilder in C#?

StringBuilder and string are both used to string values, but both have many differences on the bases of instance creation and also in performance.

16. What are sealed classes in C#?

Sealed classes are used to restrict the inheritance feature of object-oriented programming. Once a class is defined as a sealed class, the class cannot be inherited.

In C#, the sealed modifier is used to define a class as sealed. In Visual Basic .NET the Not Inheritable keyword serves the purpose of the sealed class. If a class is derived from a sealed class then the compiler throws an error.

If you have ever noticed, structs are sealed. You cannot derive a class from a struct.

17. What is a Delegate? Explain.

A Delegate is a variable that holds the reference to a method. Hence it is a function pointer or reference type. All Delegates are derived from System.Delegate namespace. Both Delegate and the method that it refers to can have the same signature.

Declaring a delegate: public delegate void AddNumbers(int n);
After the declaration of a delegate, the object must be created by the delegate using the new keyword.

1
AddNumbers an1 = new AddNumbers(number);

The delegate provides a kind of encapsulation to the reference method, which will internally get called when a delegate is called.

1
2
3
4
5
6
7
8
9
10
11
12
13
public delegate int myDel(int number);
public class Program
{
public int AddNumbers(int a)
{
int Sum = a + 10;
return Sum;
}
public void Start()
{
myDel DelgateExample = AddNumbers;
}
}

In the above example, we have a delegate myDel which takes an integer value as a parameter. Class Program has a method of the same signature as the delegate, called AddNumbers().

If there is another method called Start() which creates an object of the delegate, then the object can be assigned to AddNumbers as it has the same signature as that of the delegate.

18. What are Events?

Events are user actions that generate notifications to the application to which it must respond. The user actions can be mouse movements, keypress and so on.

Programmatically, a class that raises an event is called a publisher and a class which responds/receives the event is called a subscriber. Event should have at least one subscriber else that event is never raised.

Delegates are used to declare Events.

1
2
Public delegate void PrintNumbers();
Event PrintNumbers myEvent;

19. How to use Delegates with Events?

Delegates are used to raise events and handle them. Always a delegate needs to be declared first and then the Events are declared.

20. What do Multicast Delegates mean?

A Delegate that points to more than one method is called a Multicast Delegate. Multicasting is achieved by using + and += operator.

21. Explain Publishers and Subscribers in Events.

Publisher is a class responsible for publishing a message of different types of other classes. The message is nothing but Event as discussed in the above questions.

From the Example in Q #32, Class Patient is the Publisher class. It is generating an Event deathEvent, which is received by the other classes.

Subscribers capture the message of the type that it is interested in. Again, from the Example of Q#32, Class Insurance and Bank are Subscribers. They are interested in event deathEvent of type void.

22. What are Synchronous and Asynchronous operations?

Synchronization is a way to create a thread-safe code where only one thread can access the resource at any given time. The asynchronous call waits for the method to complete before continuing with the program flow.

Synchronous programming badly affects the UI operations when the user tries to perform time-consuming operations since only one thread will be used. In Asynchronous operation, the method call will immediately return so that the program can perform other operations while the called method completes its work in certain situations.

In C#, Async and Await keywords are used to achieve asynchronous programming. Look at Q #43 for more details on synchronous programming.

23. What is Reflection in C#?

Reflection is the ability of a code to access the metadata of the assembly during runtime. A program reflects upon itself and uses the metadata to inform the user or modify its behavior. Metadata refers to information about objects, methods.

The namespace System.Reflection contains methods and classes that manage the information of all the loaded types and methods. It is mainly used for windows applications, For Example, to view the properties of a button in a windows form.

The MemberInfo object of the class reflection is used to discover the attributes associated with a class.

Reflection is implemented in two steps, first, we get the type of the object, and then we use the type to identify members such as methods and properties.

To get type of a class, we can simply use,

1
Type mytype = myClass.GetType();

Once we have a type of class, the other information about the class can be easily accessed.

1
System.Reflection.MemberInfo Info = mytype.GetMethod(“AddNumbers”);

Above statement tries to find a method with name AddNumbers in the class myClass.

24. What is a Generic Class?

Generics or Generic class is used to create classes or objects which do not have any specific data type. The data type can be assigned during runtime, i.e when it is used in the program.

In case of other data type parameter comparisons, instead of creating many overloaded methods, we can create a generic class and pass a substitute data type, i.e T. So, T acts as a datatype until it is used specifically in the Main() method.

25. What is a Jagged Array?

A Jagged array is an array whose elements are arrays. It is also called as the array of arrays. It can be either single or multiple dimensions.

int[] jaggedArray = new int[4][];

#) Name some properties of Array.

Properties of an Array include:

  • Length: Gets the total number of elements in an array.
  • IsFixedSize: Tells whether the array is fixed in size or not.
  • IsReadOnly: Tells whether the array is read-only or not.

26. What is an Array Class?

An Array class is the base class for all arrays. It provides many properties and methods. It is present in the namespace system.

27. What is a String? What are the properties of a String Class?

A String is a collection of char objects. We can also declare string variables in c#.

string name = “C# Questions”;
A string class in C# represents a string. The properties of the string class are:

  • Chars get the Char object in the current String.
  • Length gets the number of objects in the current String.

28. Name some properties of Thread Class.

Few Properties of thread class are:

  • IsAlive – contains value True when a thread is Active.
  • Name – Can return the name of the thread. Also, can set a name for the thread.
  • Priority – returns the prioritized value of the task set by the operating system.
  • IsBackground – gets or sets a value which indicates whether a thread should be a background process or foreground.
  • ThreadState– describes the thread state.

29. What are the different states of a Thread?

Different states of a thread are:

  • Unstarted – Thread is created.
  • Running – Thread starts execution.
  • WaitSleepJoin – Thread calls sleep, calls wait on another object and calls join on another thread.
  • Suspended – Thread has been suspended.
  • Aborted – Thread is dead but not changed to state stopped.
  • Stopped – Thread has stopped.

30. What are Async and Await?

Async and Await keywords are used to create asynchronous methods in C#.

Asynchronous programming means that the process runs independently of main or other processes.

31. Async Keyword

Async keyword is used for the method declaration.

32. What is a Deadlock?

A Deadlock is a situation where a process is not able to complete its execution because two or more processes are waiting for each other to finish. This usually occurs in multi-threading.

Here a shared resource is being held by a process and another process is waiting for the first process to release it and the thread holding the locked item is waiting for another process to complete.

33. Explain Lock, Monitors, and Mutex Object in Threading.

  • Lock keyword ensures that only one thread can enter a particular section of the code at any given time. lock(ObjA) means the lock is placed on ObjA until this process releases it, no other thread can access ObjA.

  • Mutex is also like a lock but it can work across multiple processes at a time. WaitOne() is used to lock and ReleaseMutex() is used to release the lock. But Mutex is slower than lock as it takes time to acquire and release it.

  • Monitor.Enter and Monitor.Exit implements lock internally. a lock is a shortcut for Monitors. lock(objA) internally calls.

1
2
3
4
5
6
7
Monitor.Enter(ObjA);
try
{
}
Finally {
Monitor.Exit(ObjA));
}

34. What is a Race Condition?

Race condition occurs when two threads access the same resource and are trying to change it at the same time. The thread which will be able to access the resource first cannot be predicted.

If we have two threads, T1 and T2, and they are trying to access a shared resource called X. And if both the threads try to write a value to X, the last value written to X will be saved.

35. What is Thread Pooling?

Thread pool is a collection of threads. These threads can be used to perform tasks without disturbing the primary thread. Once the thread completes the task, the thread returns to the pool.

System.Threading.ThreadPool namespace has classes that manage the threads in the pool and its operations.

36. What is Serialization?

Serialization is a process of converting code to its binary format. Once it is converted to bytes, it can be easily stored and written to a disk or any such storage devices. Serializations are mainly useful when we do not want to lose the original form of the code and it can be retrieved anytime in the future.

Any class which is marked with the attribute [Serializable] will be converted to its binary form.

The reverse process of getting the C# code back from the binary form is called Deserialization.

To Serialize an object we need the object to be serialized, a stream that can contain the serialized object and namespace System.Runtime.Serialization can contain classes for serialization.

37. What are the types of Serialization?

The different types of Serialization are:

  • XML serialization – It serializes all the public properties to the XML document. Since the data is in XML format, it can be easily read and manipulated in various formats. The classes reside in System.sml.Serialization.
  • SOAP – Classes reside in System.Runtime.Serialization. Similar to XML but produces a complete SOAP compliant envelope that can be used by any system that understands SOAP.
  • Binary Serialization – Allows any code to be converted to its binary form. Can serialize and restore public and non-public properties. It is faster and occupies less space.

38. What is an XSD file?

An XSD file stands for XML Schema Definition. It gives a structure for the XML file. It means it decides the elements that the XML should have and in what order and what properties should be present. Without an XSD file associated with XML, the XML can have any tags, any attributes, and any elements.

Xsd.exe tool converts the files to the XSD format. During Serialization of C# code, the classes are converted to XSD compliant format by xsd.exe.

39. What is an Object and a Class?

  • Class is an encapsulation of properties and methods that are used to represent a real-time entity. It is a data structure that brings all the instances together in a single unit.

  • Object is defined as an instance of a Class. Technically, it is just a block of memory allocated that can be stored in the form of variables, array or a collection.

40. What are the fundamental OOP concepts?

The four fundamental concepts of Object-Oriented Programming are:

  • Encapsulation: Here, the internal representation of an object is hidden from the view outside the object’s definition. Only the required information can be accessed whereas the rest of the data implementation is hidden.
  • Abstraction: It is a process of identifying the critical behavior and data of an object and eliminating the irrelevant details.
  • Inheritance: It is the ability to create new classes from another class. It is done by accessing, modifying and extending the behavior of objects in the parent class.
  • Polymorphism: The name means, one name, many forms. It is achieved by having multiple methods with the same name but different implementations.

41. What is Managed and Unmanaged code?

Managed code is a code that is executed by CLR (Common Language Runtime) i.e all application code is based on .Net platform. It is considered as managed because of the .Net framework which internally uses the garbage collector to clear up the unused memory.

Unmanaged code is any code that is executed by application runtime of any other framework apart from .Net. The application runtime will take care of memory, security and other performance operations.

42. What is an Interface?

Interface is a class with no implementation. The only thing that it contains is the declaration of methods, properties, and events.

43. Explain Get and Set Accessor properties?

Get and Set are called Accessors. These are made use by Properties. The property provides a mechanism to read, write the value of a private field. For accessing that private field, these accessors are used.

  1. Get Property is used to return the value of a property
  2. Set Property accessor is used to set the value.

44. What is a Thread? What is Multithreading?

A Thread is a set of instructions that can be executed, which will enable our program to perform concurrent processing. Concurrent processing helps us do more than one operation at a time. By default, C# has only one thread. But the other threads can be created to execute the code in parallel with the original thread.

Thread has a life cycle. It starts whenever a thread class is created and is terminated after the execution. System.Threading is the namespace which needs to be included to create threads and use its members.

Threads are created by extending the Thread Class. Start() method is used to begin thread execution.

1
2
3
4
//CallThread is the target method//
ThreadStart methodThread = new ThreadStart(CallThread);
Thread childThread = new Thread(methodThread);
childThread.Start();

C# can execute more than one task at a time. This is done by handling different processes by different threads. This is called MultiThreading.

There are several thread methods that are used to handle multi-threaded operations: Start, Sleep, Abort, Suspend, Resume and Join.

45. What is “using” statement in C#?

“Using” keyword denotes that the particular namespace is being used by the program.

For Example, using System

Here, System is a namespace. The class Console is defined under System. So, we can use the console.writeline (“….”) or readline in our program.

46. Explain Abstraction.

Abstraction is one of the OOP concepts. It is used to display only the essential features of the class and hide unnecessary information.

Abstraction helps in knowing what is necessary and hiding the internal details from the outside world. Hiding of the internal information can be achieved by declaring such parameters as Private using the private keyword.

47. What are C# I/O classes? What are the commonly used I/O classes?

C# has System.IO namespace, consisting of classes that are used to perform various operations on files like creating, deleting, opening, closing, etc.

Some commonly used I/O classes are:

  • File – Helps in manipulating a file.
  • StreamWriter – Used for writing characters to a stream.
  • StreamReader – Used for reading characters to a stream.
  • StringWriter – Used for reading a string buffer.
  • StringReader – Used for writing a string buffer.
  • Path – Used for performing operations related to the path information.

48. What is StreamReader/StreamWriter class?

StreamReader and StreamWriter are classes of namespace System.IO. They are used when we want to read or write charact90, Reader-based data, respectively.

Some of the members of StreamReader are: Close(), Read(), Readline().

Members of StreamWriter are: Close(), Write(), Writeline().

1
2
3
4
5
6
7
8
9
10
11
Class Program1
{
using(StreamReader sr = new StreamReader(“C:\ReadMe.txt”)
{
//----------------code to read-------------------//
}
using(StreamWriter sw = new StreamWriter(“C:\ReadMe.txt”))
{
//-------------code to write-------------------//
}
}

49. What is a Destructor in C#?

Destructor is used to clean up the memory and free the resources. But in C# this is done by the garbage collector on its own. System.GC.Collect() is called internally for cleaning up. But sometimes it may be necessary to implement destructors manually.

For Example:

1
2
3
4
~Car()
{
Console.writeline(“….”);
}

50. What is an Abstract Class?

An Abstract class is a class which is denoted by abstract keyword and can be used only as a Base class. This class should always be inherited. An instance of the class itself cannot be created. If we do not want any program to create an object of a class, then such classes can be made abstract.

Any method in the abstract class does not have implementations in the same class. But they must be implemented in the child class.

For Example:

1
2
3
4
5
6
7
8
9
abstract class AB1
{
Public void Add();
}
Class childClass : AB1
{
childClass cs = new childClass ();
int Sum = cs.Add();
}

All the methods in an abstract class are implicitly virtual methods. Hence, the virtual keyword should not be used with any methods in the abstract class.

51. How can one use nullable types in .Net?

Nullable types are defined as the types which can either take the normal value or the null value.

52. How to use nullable types in .Net?

Value types can take either their normal values or a null value. Such types are called nullable types.

1
2
3
4
Int? someID = null;
If(someID.HasVAlue)
{
}

53. What is the difference between Continue and Break Statement?

Break statement breaks the loop. It makes the control of the program to exit the loop. Continue statement makes the control of the program to exit only the current iteration. It does not break the loop.

54. What is the difference between finally and finalize block?

finally block is called after the execution of try and catch block. It is used for exception handling. Regardless of whether an exception is caught or not, this block of code will be executed. Usually, this block will have a clean-up code.

finalize method is called just before garbage collection. It is used to perform clean up operations of Unmanaged code. It is automatically called when a given instance is not subsequently called.

55. What is an Array? Give the syntax for a single and multi-dimensional array?

An Array is used to store multiple variables of the same type. It is a collection of variables stored in a contiguous memory location.

For Example:

1
2
double numbers = new double[10];
int[] score = new int[4] {25,24,23,25};

A single dimensional array is a linear array where the variables are stored in a single row. Above example is a single dimensional array.

Arrays can have more than one dimension. Multidimensional arrays are also called rectangular arrays.

For Example, int[,] numbers = new int[3,2] { {1,2} ,{2,3},{3,4} };

56. What are Boxing and Unboxing?

Converting a value type to reference type is called ‘Boxing’. Explicit conversion of the same reference type that is created by boxing back to value type is called ‘Unboxing’.

57. What is an Array used for?

An Array is used to store multiple variables of the same type and is a collection of variables stored in a contiguous memory location.

58. What is an Escape Sequence? Name the sequences in C

An Escape sequence is denoted by a backslash (). The backslash indicates that the character that follows it should be interpreted literally or that it is a special character. An escape sequence is considered as a single character.

59. What are the basic String Operations?

The basic String Operations are: Concatenate, Modify, Search, Compare.

60. What is an Escape Sequence? Name some String escape sequences in C#.

An Escape sequence is denoted by a backslash (). The backslash indicates that the character that follows it should be interpreted literally or it is a special character. An escape sequence is considered as a single character.

String escape sequences are as follows:

  • \n – Newline character
  • \b – Backspace
  • \ – Backslash
  • \’ – Single quote
  • \’’ – Double Quote

    61. In C#.Net, what do indexers mean?

    In C#, indexers are also known as smart arrays. They allow the instances of the class that are to be indexed in a similar as that of the array.

62. What are Regular expressions? Search a string using regular expressions?

Regular expression is a template to match a set of input. The pattern can consist of operators, constructs or character literals. Regex is used for string parsing and replacing the character string.

For Example:

  • matches the preceding character zero or more times. So, a*b regex is equivalent to b, ab, aab, aaab and so on.

Searching a string using Regex:

1
2
3
4
5
6
7
8
9
10
11
static void Main(string[] args)
{
string[] languages = { "C#", "Python", "Java" };
foreach(string s in languages)
{
if(System.Text.RegularExpressions.Regex.IsMatch(s,"Python"))
{
Console.WriteLine("Match found");
}
}
}

The above example searches for “Python” against the set of inputs from the languages array. It uses Regex.IsMatch which returns true in case if the pattern is found in the input. The pattern can be any regular expression representing the input that we want to match.

63. State the difference between direct cast and ctype.

The difference between direct cast and ctype is that direct cast is used for the conversion of type of an object that requires the run time which is similar to the specified type in the direct cast. Whereas ctype is used for converting the conversion which is defined for the expression and the type.

64. How can one use the singleton design pattern in C#?

The singleton design pattern is used in C# when the class has one instance and the access is provided globally.

65. What are the basic String Operations? Explain.

Some of the basic string operations are:

  • Concatenate: Two strings can be concatenated either by using a System.String.Concat or by using + operator.
  • Modify: Replace(a,b) is used to replace a string with another string. Trim() is used to trim the string at the end or at the beginning.
  • Compare: System.StringComparison() is used to compare two strings, either a case-sensitive comparison or not case sensitive. Mainly takes two parameters, original string, and string to be compared with.
  • Search: StartWith, EndsWith methods are used to search a particular string.

66. What is Parsing? How to Parse a Date Time String?

Parsing converts a string into another data type.

For Example:

1
2
string text = “500”;
int num = int.Parse(text);

500 is an integer. So, the Parse method converts the string 500 into its own base type, i.e int.

Follow the same method to convert a DateTime string.

1
2
string dateTime = “Jan 1, 2018”;
DateTime parsedValue = DateTime.Parse(dateTime);

67. What are extension methods in C#?

Extension methods enable you to add methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.

An extension method is a special kind of static method, but they are called as if they were instance methods on the extended type.

68. What is the difference between the Virtual method and the Abstract method?

The Virtual method must always have a default implementation. However, it can be overridden in the derived class, although it is not mandatory. It can be overridden using the override keyword.

An Abstract method does not have an implementation. It resides in the abstract class. It is mandatory that the derived class implements the abstract method. An override keyword is not necessary here though it can be used.

69. What are the types of errors in C#?

Answer: Following are the two types of error in C#:

  1. Compile-time error
  2. Run time error

70. What is the difference between method overriding and method overloading?

In method overriding, we change the method definition in the derived class that changes the method behavior.

Method overloading is creating a method with the same name within the same class having different signatures.

71. Why can’t you specify the accessibility modifier for methods inside the interface?

In an interface, we have virtual methods that do not have method definition. All the methods are there to be overridden in the derived class. That’s why they all are public.

72. What is an object pool in .NET?

An object pool is a container having objects ready to be used. It tracks the object that is currently in use, total number of objects in the pool. This reduces the overhead of creating and re-creating objects.

73. What is the difference between read-only and constant?

The difference between read-only and constant is that read-only is used during run time when the value has to be assigned. Constant variables are used during compilation time for declaration and initialization.

74. What are partial classes?

A partial class is only used to split the definition of a class in two or more classes in the same source code file or more than one source file. You can create a class definition in multiple files, but it will be compiled as one class at run time. Also, when you create an instance of this class, you can access all the methods from all source files with the same object.

Partial Classes can be created in the same namespace. It isn’t possible to create a partial class in a different namespace. So use the “partial” keyword with all the class names that you want to bind together with the same name of a class in the same namespace.

75. Can “this” be used in a static method?

No, “this” cannot be used in a static method as static methods are used for either static variables or static methods.

76. What is IEnumerable<> in C#?

IEnumerable is the parent interface for all non-generic collections in System.Collections namespace like ArrayList, HastTable etc. that can be enumerated. For the generic version of this interface as IEnumerable which a parent interface of all generic collections class in System.Collections.Generic namespace like List<> and more.

In System.Collections.Generic.IEnumerable have only a single method which is GetEnumerator() that returns an IEnumerator. IEnumerator provides the power to iterate through the collection by exposing a Current property and Move Next and Reset methods if we don’t have this interface as a parent so we can’t use iteration by foreach loop or can’t use that class object in our LINQ query.

77. What is the difference between late binding and early binding in C#?

Early Binding and Late Binding concepts belong to polymorphism in C#. Polymorphism is the feature of object-oriented programming that allows a language to use the same name in different forms. For example, a method named Add can add integers, doubles, and decimals.

78. What is the Constructor Chaining in C#?

Constructor chaining is a way to connect two or more classes in a relationship as Inheritance. In Constructor Chaining, every child class constructor is mapped to a parent class Constructor implicitly by base keyword, so when you create an instance of the child class, it will call the parent’s class Constructor. Without it, inheritance is not possible.

79. What’s the difference between the Array.CopyTo() and Array.Clone()?

The Array.Clone() method creates a shallow copy of an array. A shallow copy of an Array copies only the elements of the Array, whether they are reference types or value types, but it does not copy the objects that the references refer to. The references in the new Array point to the same objects that the references in the original Array point to.

The CopyTo() static method of the Array class copies a section of an array to another array. The CopyTo method copies all the elements of an array to another one-dimension array. The code listed in Listing 9 copies contents of an integer array to an array of object types.

80. Can Multiple Catch Blocks be executed in C#?

We can use multiple catch blocks with a try statement. Each catch block can catch a different exception. The following code example shows how to implement multiple catch statements with a single try statement.

81. What are Value types and Reference types in C#?

In C#, data types can be of two types, value types, and reference types. Value type variables contain their object (or data) directly. If we copy one value type variable to another then we are actually making a copy of the object for the second variable. Both of them will independently operate on their values, Value type data types are stored on a stack and reference data types are stored on a heap.

In C#, basic data types include int, char, bool, and long, which are value types. Classes and collections are reference types.

82. How do you use the “using” statement in C#?

There are two ways to use the using keyword in C#. One is as a directive and the other is as a statement. Let’s explain!

  1. using Directive
    Generally, we use the using keyword to add namespaces in code-behind and class files. Then it makes available all the classes, interfaces and abstract classes and their methods and properties on the current page. Adding a namespace can be done in the following two ways:
  2. Using Statement
    This is another way to use the using keyword in C#. It plays a vital role in improving performance in Garbage Collection.

83. What are Anonymous Types in C#?

Anonymous types allow us to create new types without defining them. This is a way of defining read-only properties in a single object without having to define each type explicitly. Here, Type is generated by the compiler and is accessible only for the current block of code. The type of properties is also inferred by the compiler.

We can create anonymous types by using “new” keyword together with the object initializer.

84. Explain “static” keyword in C#?

“Static” keyword can be used for declaring a static member. If the class is made static then all the members of the class are also made static. If the variable is made static then it will have a single instance and the value change is updated in this instance.

85. What are the different types of classes in C#?

The different types of class in C# are

  1. Partial class – Allows its members to be divided or shared with multiple .cs files. It is denoted by the keyword ‘Partial’.
    Sealed class – It is a class that cannot be inherited. To access the members of a sealed class, we need to create the object of the class. It is denoted by the keyword ‘Sealed’.
  2. Abstract class – It is a class whose object cannot be instantiated. The class can only be inherited. It should contain at least one method. It is denoted by the keyword ‘abstract’.
  3. Static class – It is a class which does not allow inheritance. The members of the class are also static. It is denoted by the keyword ‘static’. This keyword tells the compiler to check for any accidental instances of the static class.

86. What is Managed and Unmanaged code?

Managed code is a code that is executed by CLR (Common Language Runtime). It is called ‘managed code’ because of the .Net framework which uses the garbage collector internally to clear up unused memory. ‘__Unmanaged code’ is any code that is executed by the application runtime of any other framework apart from .Net. The application runtime will take care of security, memory and other performance operations.

87. Explain Namespaces in C#

Namespaces are used to organize large code projects. “System” is the most widely-used namespace in C#.

88. Explain Polymorphism

In programming, polymorphism means the same method but different implementations. It contains two types, Compile-time and Runtime. Compile time polymorphism is accomplished by operator overloading. Runtime polymorphism is accomplished by overriding. An example would be: a class has a method Void Add(), polymorphism is accomplished by Overloading the method, that is, void Add(int a, int b), void Add(int add) are all overloaded methods.

89. How is Exception Handling implemented in C#?

Exception handling is done using four keywords in C#:

  1. Try – contains a block of code that checks an exception.
  2. Catch – is a program that catches an exception with the help of exception handler.
  3. Finally – is a block of code written to execute even if an exception is not caught.
  4. Throw – Throws an exception when a problem occurs.

问题

umi推荐使用yarn安装,安装umi后,使用umi提示不是内部或者外部命令。(’umi’ is not recognized as an internal or external command,operable program or batch file.)

解决

根源在于yarn的global bin目录不在path环境变量的中,解决办法:

  1. 执行yarn global bin, 得到global bin目录
  2. global bin目录添加到环境变量path
  3. 测试 umi -v

问题

最近访问GitHub总是不稳定,经常连不上, 出各种错误(OpenSSL SSL_read: Connection was reset, errno 10054, Connection refused …)。

原因大概是GitHub的IP经常变化(一天可能变几次),我们本地的DNS解析有问题,解决办法就是查询github的IP,手工写到我们的hosts文件中。

查询GitHub最新IP

  1. 访问 https://github.com.ipaddress.com/
  2. IP Address 即为IP地址
    github ip

修改hosts文件

  1. 目录:C:\Windows\System32\drivers\etc
  2. 打开 hosts文件
  3. 结尾增加一行 140.82.112.4 github.com (IP 用你查询到的最新的IP)
  4. 搞定,测试一下

说明,hosts文件, 可以给github.com添加多条IP记录,这样当我们访问github时,会一次尝试每个IP是否可以访问,如果都不行,会去Internet上做DNS解析。
可以这样配置

1
2
3
4
140.82.112.4	github.com
140.82.113.4 github.com
140.82.112.3 github.com
140.82.114.4 github.com

https://jackniu81.github.io/2021/04/18/Algorithm-Fibonacci-numbers/

1. 斐波那契数列

斐波那契数列:0, 1, 1, 2, 3, 5, 8, 13 … …

通常用 F(n) 表示,形成的序列称为 斐波那契数列 。该数列由 0 和 1 开始,后面的每一项数字都是前面两项数字的和。

1
2
F(0) = 0,F(1) = 1
F(n) = F(n - 1) + F(n - 2),其中 n > 1

敏捷开发时,我们估算Story Point,通常就是使用斐波那契数列。

2. 解题思路

2.1. 递归

F(n) = F(n - 1) + F(n - 2), 很简单,就不谈了。

2.2. 动态规划

动态规划的思想是,记录中间计算结果,计算后面相时,根据前面保存的结果直接计算,避免重复计算。

3. Javascript 实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* @param {number} n
* @return {number}
*/
var fib = function(n) {
if(n===0)
return 0;
if(n===1)
return 1;

let arr = [0,1]
for(let i=2;i<=n;i++){
arr[i] = arr[i-1] + arr[i-2];
}
return arr[n];
};

还可以进一步优化,当前使用数组记录以及计算过的F(n),由于F(n) = F(n - 1) + F(n - 2),实际只需要记录最近的2个值即可,不需要使用数组记录全部数据。

1. NET/dotnet core/.NET framework 的关系?

先看 2 张图
最新的.NET 5 的示意图
.NET 5
之前的(dotnet core3.x 时代)的示意图
dotnet core .3.1
总结如下:

  1. 2016 年开始,分开了.NET Framework 和.NET Core,后者开源、面向跨平台应用;
  2. 2019 年,.NET Framework 和.NET Core 被.NET5 完成了统一。未来只会有一个.NET,可以支持 Windows、Linux、macOS、iOS、Android、tvOS、watchOS 和 WebAssembly,等等
  3. .Net standard library 是之前.NET Framework 和.NET Core 公共的部分;

2. corefx, coreclr 都是什么?

dotnet 组织包含了.NET Core 的核心代码, 包括 coreclr 和 corefx 等.

  1. coreclr 是运行时代码,
  2. corefx 是各种基础类库的代码. CoreFX 主要包含数个公共库,例如 System.Collections, System.IO, System.Xml 等。

3. asp.net core

3.1. Kestrel

Kestrel 是 asp.net core 引入的跨平台的网络服务器,是默认配置。可以没有 iis, apache 和 nginx 就可以单独运行。
Kestrel 基于 libuv 实现;(node.js 也是基于 libuv)

3.2. asp.net core 主要的特性

  1. 依赖注入。
  2. 日志系统架构。
  3. 引入了一个跨平台的网络服务器,kestrel。可以没有 iis, apache 和 nginx 就可以单独运行。
  4. 可以使用命令行创建应用。
  5. 使用 AppSettings.json 来配置工程。
  6. 使用 start up 来注册服务。
  7. 更好的支持异步编程。
  8. 支持 web socket 和 signal IR。
  9. 对于跨网站的请求的预防和保护机制。

3.3. startup class 的作用?

Startup class 是 dot net core 应用的入口。所有的 dot net core 应用必须有这个 class。这个类用来配置应用。这个类的调用是在 program main 函数里面进行配置的。类的名字可以自己定义。

3.4. Startup class 的 config service 方法有什么作用?

在这个方法里我们可以添加一些 service 进入依赖注入容器。

3.5. startup class 的 configure 方法有什么作用?

这个方法来定义整个应用如何响应 HTTP 请求。它有几个比较重要的参数,application builder,Hosting environment, logo factory, 在这里我们可以配置一些中间件用来处理路径,验证和 session 等等。

3.6. 什么是 meta packages?

Meta packages 是指包含所有 ASP dot net code 依赖的一个包。叫做 Microsoft.AspNetCore.All

3.7. 什么是中间件?

中间件在这里是指注入到应用中处理请求和响应的组件。asp.net core 的中间件模型也是洋葱模型(和 node.js d Koa 一样)

3.8. application builder 的 use 和 run 方法有什么区别?

这两个方法都在 start up class 的 configure 方法里面调用。都是用来向应用请求管道里面添加中间件的。Use 方法可以调用下一个中间件的添加,而 run 不会。

3.9. dot net core 管道(pipeline)里面的 map 拓展有什么作用?

可以针对不同的路径添加不同的中间件。

1
2
3
4
5
public void Configure(IApplicationBuilder app)
{
app.Map("/path1", Middleware1);
app.Map("/path2", Middleware2);
}

3.10. 如何在 dot net core 中激活 session 功能?

  1. 首先要添加 session 包.
  2. 其次要在 config service 方法里面添加 session。
  3. 然后又在 configure 方法里面调用 usesession。

3.11. 如何在 controller 中注入 service?

依赖注入的思想:

  1. 在 config services 方法中配置这个 service。
  2. 在 controller 的构造函数中,添加这个依赖注入。

3.12. dot net core 里面的路径是如何处理的?

路径处理是用来为进入的请求寻找处理函数的机制。所有的路径在函数运行开始时进行注册。

主要有两种路径处理方式:

  1. 常规路径处理就是用 MapRoute 的方式设定调用路径
  2. 属性路径处理是指在调用函数的上方设定一个路径属性。

3.13. application builder 的 use 和 run 方法有什么区别?

这两个方法都在 start up class 的 configure 方法里面调用。都是用来向应用请求管道里面添加中间件的。Use 方法可以调用下一个中间件的添加,而 run 不会。

3.14. 依赖注入后的服务生命周期?

在 dot net core 中,我们不需要关心如何释放这些服务, 因为系统会帮我们释放掉。有三种服务的生命周期。

  1. 单实例服务, 通过 add singleton 方法来添加。在注册时即创建服务, 在随后的请求中都使用这一个服务。
  2. 短暂服务, 通过 add transient 方法来添加。是一种轻量级的服务,用于无状态服务的操作。
  3. 作用域服务,一个新的请求会创建一个服务实例。使用 add scoped 方法来添加。

3.15. 什么么是 Razor 页面?

是 dot net core 中支持 ASP 网页表格的一种开发模型。@page 作为页面的起始标志。可以看做是 asp.net core 使用的模板引擎。

3.16. 如何在 Razor 页面中实现数据模型绑定?

使用 bindproperty 属性。

3.17. Server.Transfer 和 Response.Redirect 的区别是什么

  1. Server.Transfer 仅是服务器中控制权的转向,在客户端浏览器地址栏中不会显示出转向后的地址;
  2. Response.Redirect 则是完全的跳转,浏览器将会得到跳转的地址,并重新发送请求链接。这样,从浏览器的地址栏中可以看到跳转后的链接地址。

3.18. API,什么时候用 Get/Post/Put/Delete

  1. GET: 查询
  2. POST :创建对象
  3. PUT: 修改对象
  4. DELETE:删除

4. C#

4.1. 一个单例(Singleton)类

单线程下的简单实现:

1
2
3
4
5
public MySingleton
{
private MySingleton(){} // 禁止被实例化
public readonly static MySingletonInstance = new MySingleton(); // 程序加载时就会初始化
}

线程安全的加锁双检查

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class MySingleton
{
private static MySingleton _instance = null;
private static readonly object SynObject = new object();

MySingleton() { }

public static MySingleton Instance
{
get
{
if (null == _instance)
{
lock (SynObject)
{
if (null == _instance)
{
_instance = new MySingleton();
}
}
}
return _instance;
}
}
}

4.2. abstract class 和 interface 有什么区别?

相同点:都不能被直接实例化,都可以通过继承实现其抽象方法。

不同点:

  1. 接口支持多继承;抽象类不能实现多继承。
  2. 接口只能定义行为;抽象类既可以定义行为,还可能提供实现。
  3. 接口只包含方法(Method)、属性(Property)、索引器(Index)、事件(Event)的签名,但不能定义字段和包含实现的方法;
  4. 抽象类可以定义字段、属性、包含有实现的方法。

4.3. 是否可以继承 String 类?

String 类是 sealed 类故不可以继承。

4.4. StringBuilder 和 String 的区别?

String 在进行运算时(如赋值、拼接等)会产生一个新的实例,而 StringBuilder 则不会。所以在大量字符串拼接或频繁对某一字符串进行操作时最好使用 StringBuilder,不要使用 String。
但是简单的字符拼接,String 还是首选。(100?次以内用 String,以上用 StringBuilder)

4.5. 什么情况下会用到虚方法?它与接口有什么不同?

  1. 子类重新定义父类的某一个方法时,必须把父类的方法定义为 virtual
  2. 在定义接口中不能有方法体,虚方法可以。
  3. 实现时,子类可以不重新定义虚方法,但如果一个类继承接口,那必须实现这个接口。

4.6. string、String;int、Int32;Boolean、bool 的区别

String、Int32、Boolean 等都属于.Net 中定义的类,而 string、int、bool 相当于 C#中对这些类定义的别名。CTS。

4.7. private、 protected、 public、 internal 修饰符的访问权限。

  1. private : 私有成员, 在类的内部才可以访问。
  2. protected : 保护成员,该类内部和继承类中可以访问。
  3. public : 公共成员,完全公开,没有访问限制。
  4. internal: 当前程序集内可以访问。

4.8. C#中的委托是什么?事件是不是一种委托?事件和委托的关系。

委托可以把一个方法作为参数代入另一个方法,可以理解为指向一个函数的指针。
换个说法来解释,委托就是函数指针,事件就是保存多个函数指针的数组。

事件和委托的区别如下:

  1. 事件只能在方法的外部进行声明,而委在方法的外部和内部都可以声明。
  2. 事件只能在类的内部触发,不能在类的外部触发。而委托在类的内部和外都都可以触发。
  3. 委托一般用于回调,而事件用于外部接口。例如在观察者模式中,在被观察者中可以声明一个事件作为外部观察者注册的接口。

4.9. override 与重载(overload)的区别

  1. 重载是方法的名称相同。参数或参数类型不同,进行多次重载以适应不同的需要。重载(overload)是面向过程的概念。
  2. Override 是进行基类中函数的重写。Override 是面向对象的概念

4.10. 什么是装箱(boxing)和拆箱(unboxing)

装箱:从值类型接口转换到引用类型。
拆箱:从引用类型转换到值类型。

——–END——–

参考:
https://www.webtrainingroom.com/interview/asp-net-core-interview-questions-answers > https://www.talkingdotnet.com/asp-net-core-interview-questions/

—————- END —————-

1. 基本问题

1.1. Vue.js 的特点

  • 易用: 简单,易学,上手快
  • 灵活: (渐进式)不断繁荣的生态系统,可以在一个库和一套完整框架之间自如伸缩。
  • 高效: 20kB min+gzip 运行大小;超快虚拟 DOM;最省心的优化
  • 双向绑定:开发效率高
  • 基于组件的代码共享
  • Web项目工程化,增加可读性、可维护性

1.2. Vue.js 双向绑定的原理

Vue.js 2.0 采用数据劫持(Proxy 模式)结合发布者-订阅者模式(PubSub 模式)的方式,通过 Object.defineProperty()来劫持各个属性的 setter,getter,在数据变动时发布消息给订阅者,触发相应的监听回调。

每个组件实例都有相应的watcher程序实例,它会在组件渲染的过程中把属性记录为依赖,之后当依赖项的setter被调用时,会通知watcher重新计算,从而致使它关联的组件得以更新。

Vue.js 3.0, 放弃了Object.defineProperty ,使用更快的ES6原生 Proxy (访问对象拦截器, 也称代理器)

步骤:

  1. 需要observe的数据对象进行递归遍历,包括子属性对象的属性,都加上setter和getter这样的话,给这个对象的某个值赋值,就会触发setter,那么就能监听到了数据变化

  2. compile解析模板指令,将模板中的变量替换成数据,然后初始化渲染页面视图,并将每个指令对应的节点绑定更新函数,添加监听数据的订阅者,一旦数据有变动,收到通知,更新视图

  3. Watcher订阅者是Observer和Compile之间通信的桥梁,主要做的事情是: ①在自身实例化时往属性订阅器(dep)里面添加自己 ②自身必须有一个update()方法 ③待属性变动dep.notice()通知时,能调用自身的update()方法,并触发Compile中绑定的回调,则功成身退。

  4. MVVM作为数据绑定的入口,整合Observer、Compile和Watcher三者,通过Observer来监听自己的model数据变化,通过Compile来解析编译模板指令,最终利用Watcher搭起Observer和Compile之间的通信桥梁,达到数据变化 -> 视图更新;视图交互变化(input) -> 数据model变更的双向绑定效果。

1.3. Vue.js 3.0 放弃defineProperty, 使用Proxy的原因

Object.defineProperty缺陷

  1. 监控到数组下标的变化时,开销很大。所以Vue.js放弃了下标变化的检测;
  2. Object.defineProperty只能劫持对象的属性,而Proxy是直接代理对象。Object.defineProperty需要遍历对象的每个属性,如果属性值也是对象,则需要深度遍历。而 Proxy 直接代理对象,不需要遍历操作。
  3. Object.defineProperty对新增属性需要手动进行Observe。vue2时需要使用 vm.$set 才能保证新增的属性也是响应式
  4. Proxy支持13种拦截操作,这是defineProperty所不具有的
  5. Proxy 作为新标准,长远来看,JS引擎会继续优化 Proxy,但 getter 和 setter 基本不会再有针对性优化

1.4. Vue 2 中给 data 中的对象属性添加一个新的属性时会发生什么?如何解决?

视图并未刷新。这是因为在Vue实例创建时,新属性并未声明,因此就没有被Vue转换为响应式的属性,自然就不会触发视图的更新,这时就需要使用Vue的全局 api $set():this.$set(this.obj, 'new_property', 'new_value')

1.5. Computed和Watch的区别

  1. computed 计算属性 : 依赖其它属性值,并且 computed 的值有缓存,只有它依赖的 属性值发生改变,下一次获取 computed 的值时才会重新计算 computed 的值。
  2. watch 侦听器 : 更多的是观察的作用,无缓存性,类似于某些数据的监听回调,每 当监听的数据变化时都会执行回调进行后续操作。

运用场景:

  1. 当我们需要进行数值计算,并且依赖于其它数据时,应该使用 computed,因为可以利用 computed 的缓存特性,避免每次获取值时,都要重新计算。
  2. 当我们需要在数据变化时执行异步或开销较大的操作时,应该使用 watch,使用 watch 选项允许我们执行异步操作 ( 访问一个 API ),限制我们执行该操作的频率, 并在我们得到最终结果前,设置中间状态。这些都是计算属性无法做到的。
  3. 多个因素影响一个显示,用Computed;一个因素的变化影响多个其他因素、显示,用Watch;

1.6. Computed 和 Methods 的区别

  1. computed: 计算属性是基于它们的依赖进行缓存的,只有在它的相关依赖发生改变时才会重新求值对于 method ,只要发生重新渲染,
  2. method 调用总会执行该函数

1.7. 虚拟DOM,diff算法

(1)让我们不用直接操作DOM元素,只操作数据便可以重新渲染页面
(2)虚拟dom是为了解决浏览器性能问题而被设计出来的
当操作数据时,将改变的dom元素缓存起来,都计算完后再通过比较映射到真实的dom树上
(3)diff算法比较新旧虚拟dom。如果节点类型相同,则比较数据,修改数据;如果节点不同,直接干掉节点及所有子节点,插入新的节点;如果给每个节点都设置了唯一的key,就可以准确的找到需要改变的内容,否则就会出现修改一个地方导致其他地方都改变的情况。比如A-B-C-D, 我要插入新节点A-B-M-C-D,实际上改变的了C和D。但是设置了key,就可以准确的找到B C并插入

1.8. 为何需要Virtual DOM?

  1. 具备跨平台的优势
  2. 操作 DOM 慢,js运行效率高。我们可以将DOM对比操作放在JS层,提高效率。
  3. 提升渲染性能

1.9. 过滤器 (Filter)

在Vue中使用filters来过滤(格式化)数据,filters不会修改数据,而是过滤(格式化)数据,改变用户看到的输出(计算属性 computed ,方法 methods 都是通过修改数据来处理数据格式的输出显示。
使用场景: 比如需要处理时间、数字等的的显示格式;

1.10. 常见的事件修饰符及其作用

  1. .stop:等同于 JavaScript 中的 event.stopPropagation() ,防止事件冒泡;
  2. .prevent :等同于 JavaScript 中的 event.preventDefault() ,防止执行预设的行为(如果事件可取消,则取消该事件,而不停止事件的进一步传播);
  3. .capture :当元素发生冒泡时,先触发带有该修饰符的元素。若有多个该修饰符,则由外而内触发。如 div1中嵌套div2中嵌套div3.capture中嵌套div4,那么执行顺序为:div3=》div4=》div2=》div1
  4. .self :只会触发自己范围内的事件,不包含子元素;
  5. .once :只会触发一次。

1.11. v-show指令和v-if指令的区别是什么?

v-show 仅仅控制元素的显示方式,将 display 属性在 block 和 none 来回切换;而v-if会控制这个 DOM 节点的存在与否。当我们需要经常切换某个元素的显示/隐藏时,使用v-show会更加节省性能上的开销;当只需要一次显示或隐藏时,使用v-if更加合理。

1.12. v-model 是如何实现的,语法糖实际是什么

  1. 作用在表单元素上v-model="message"等同于v-bind:value="message" v-on:input="message=$event.target.value"
  2. 作用在组件上, 本质是一个父子组件通信的语法糖,通过prop和$.emit实现, 等同于:value="message" @input=" $emit('input', $event.target.value)"

1.13. data为什么是一个函数而不是对象

JavaScript中的对象是引用类型的数据,当多个实例引用同一个对象时,只要一个实例对这个对象进行操作,其他实例中的数据也会发生变化。

而在Vue中,我们更多的是想要复用组件,那就需要每个组件都有自己的数据,这样组件之间才不会相互干扰。

所以组件的数据不能写成对象的形式,而是要写成函数的形式。数据以函数返回值的形式定义,这样当我们每次复用组件的时候,就会返回一个新的data,也就是说每个组件都有自己的私有数据空间,它们各自维护自己的数据,不会干扰其他组件的正常运行。

1.14. Vue template 到 render 的过程

  1. 调用parse方法将template转化为ast(抽象语法树, abstract syntax tree)
  2. 对静态节点做优化。如果为静态节点,他们生成的DOM永远不会改变,这对运行时模板更新起到了极大的优化作用。
  3. 生成渲染函数. 渲染的返回值是VNode,VNode是Vue的虚拟DOM节点,里面有(标签名,子节点,文本等等)

1.15. Vue data 中某一个属性的值发生改变后,视图会立即同步执行重新渲染吗?

不会立即同步执行重新渲染。
Vue 实现响应式并不是数据发生变化之后 DOM 立即变化,而是按一定的策略进行 DOM 的更新。
Vue 在更新 DOM 时是异步执行的。只要侦听到数据变化, Vue 将开启一个队列,并缓冲在同一事件循环中发生的所有数据变更。

如果同一个watcher被多次触发,只会被推入到队列中一次。这种在缓冲时去除重复数据对于避免不必要的计算和 DOM 操作是非常重要的。
然后,在下一个的事件循环”tick”中,Vue 刷新队列并执行实际(已去重的)工作。

1.16. axios是什么

易用、简洁且高效的http库, 支持node端和浏览器端,支持Promise,支持拦截器等高级配置。

1.17. sass是什么?如何在vue中安装和使用?

sass是一种CSS预编译语言安装和使用步骤如下。

  1. 用npm安装加载程序( sass-loader、 css-loader等加载程序)。
  2. 在 webpack.config.js中配置sass加载程序。

1.18. Vue.js页面闪烁

Vue. js提供了一个v-cloak指令,该指令一直保持在元素上,直到关联实例结束编译。当和CSS一起使用时,这个指令可以隐藏未编译的标签,直到实例编译结束。用法如下。

1
2
3
4
[v-cloak]{ 
 display:none;
}
<div v-cloak>{{ title }}</div>

1.19. 如何解决数据层级结构太深的问题

在开发业务时,经常会岀现异步获取数据的情况,有时数据层次比较深,如以下代码: span 'v-text="a.b.c.d"></span>, 可以使用vm.$set手动定义一层数据: vm.$set("demo",a.b.c.d)

1.20. 在 Vue. js开发环境下调用API接口,如何避免跨域

config/ index.js内对 proxyTable项配置代理。

1.21. 批量异步更新策略

Vue 在修改数据后,视图不会立刻更新,而是等同一事件循环中的所有数据变化完成之后,再统一进行视图更新。
换句话说,只要观察到数据变化,就会自动开启一个队列,并缓冲在同一个事件循环中发生的所以数据改变。在缓冲时会去除重复数据,从而避免不必要的计算和 DOM 操作。

1.22. vue 的 nextTick 方法的实现原理

  1. vue 用异步队列的方式来控制 DOM 更新和 nextTick 回调先后执行
  2. microtask 因为其高优先级特性,能确保队列中的微任务在一次事件循环前被执行完毕

1.23. Vue 组件 data 为什么必须是函数 ?

因为组件是可以复用的,JS 里对象是引用关系,如果组件 data 是一个对象,那么子组件中的 data 属性值会互相污染。
所以一个组件的 data 选项必须是一个函数,因此每个实例可以维护一份被返回对象的独立的拷贝。

1.24. v-if和v-for一起使用的弊端及解决办法

由于v-for的优先级比v-if高,所以导致每循环一次就会去v-if一次,而v-if是通过创建和销毁dom元素来控制元素的显示与隐藏,所以就会不停的去创建和销毁元素,造成页面卡顿,性能下降。

解决办法:

  1. 在v-for的外层或内层包裹一个元素来使用v-if
  2. 用computed处理

1.25. vue常用指令

  1. v-model 多用于表单元素实现双向数据绑定(同angular中的ng-model)
  2. v-bind 动态绑定 作用: 及时对页面的数据进行更改
  3. v-on:click 给标签绑定函数,可以缩写为@,例如绑定一个点击函数 函数必须写在methods里面
  4. v-for 格式: v-for=”字段名 in(of) 数组json” 循环数组或json(同angular中的ng-repeat)
  5. v-show 显示内容 (同angular中的ng-show)
  6. v-hide 隐藏内容(同angular中的ng-hide)
  7. v-if 显示与隐藏 (dom元素的删除添加 同angular中的ng-if 默认值为false)
  8. v-else-if 必须和v-if连用
  9. v-else 必须和v-if连用 不能单独使用 否则报错 模板编译错误
  10. v-text 解析文本
  11. v-html 解析html标签
  12. v-bind:class 三种绑定方法 1、对象型 ‘{red:isred}’ 2、三元型 ‘isred?”red”:”blue”‘ 3、数组型 ‘[{red:”isred”},{blue:”isblue”}]’
  13. v-once 进入页面时 只渲染一次 不在进行渲染
  14. v-cloak 防止闪烁
  15. v-pre 把标签内部的元素原位输出

1.26. 组件传值方式有哪些

  1. 父传子:子组件通过props[‘xx’] 来接收父组件传递的属性 xx 的值
  2. 子传父:子组件通过 this.$emit(‘fnName’,value) 来传递,父组件通过接收 fnName 事件方法来接收回调
  3. 其他方式:通过创建一个bus,进行传值
  4. 使用Vuex

1.27. vue-loader是什么?使用它的用途有哪些?

2. 组件 Component

2.1. vue中如何编写可复用的组件 (编写组件的原则)

  1. 以组件功能命名
  2. 只负责ui的展示和交互动画,不要在组件里与服务器打交道(获取异步数据等)
  3. 可复用组件不会因组件使用的位置、场景而变化。尽量减少对外部条件的依赖。

2.2. 如何让CSS只在当前组件中起作用?

在每一个Vue.js组件中都可以定义各自的CSS、 JavaScript代码。如果希望组件内写的CSS只对当前组件起作用,只需要在Style标签添加Scoped属性,即

2.3. keep-alive是什么?

如果需要在组件切换的时候,保存一些组件的状态防止多次渲染,就可以使用 keep-alive 组件包裹需要保存的组件。

两个重要属性,include 缓存组件名称,exclude 不需要缓存的组件名称。

2.4. 如何在 Vue. js动态插入图片

对“src”属性插值将导致404请求错误。应使用 v-bind:src (简写:src)格式代替。

2.5. 父子组件的生命周期顺序

  1. 加载渲染过程:
    父beforeCreate->父created->父beforeMount->子beforeCreate->子created->子beforeMount->子mounted->父mounted
  2. 子组件更新过程:父beforeUpdate->子beforeUpdate->子updated->父updated
  3. 父组件更新过程:父beforeUpdate->父updated
  4. 销毁过程:父beforeDestroy->子beforeDestroy->子destroyed->父destroyed

3. Vuex

3.1. vuex的核心概念

  1. state => 基本数据
  2. getters => 从基本数据派生的数据
  3. mutations => 修改数据,同步
  4. actions => 修改数据,异步 (Action 提交的是 mutation,而不是直接变更状态)
  5. modules => 模块化Vuex

3.2. vuex是什么?怎么使用?哪种功能场景使用它?

Vuex 是一个专为 Vue.js 应用程序开发的状态管理器,采用集中式存储管理应用的所有组件的状态,主要是为了多页面、多组件之间的通信。
Vuex有5个重要的属性,分别是 State、Getter、Mutation、Action、Module,由 view 层发起一个 Action 给 Mutation,在 Mutation 中修改状态,返回新的状态,通过 Getter暴露给 view层的组件或者页面,页面监测到状态改变于是更新页面。如果你的项目很简单,最好不要使用 Vuex,对于大型项目,Vuex 能够更好的帮助我们管理组件外部的状态,一般可以运用在购物车、登录状态、播放等场景中。

3.3. 多个组件之间如何拆分各自的state,每块小的组件有自己的状态,它们之间还有一些公共的状态需要维护,如何思考这块

  1. 公共的数据部分可以提升至和他们最近的父组件,由父组件派发
  2. 公共数据可以放到vuex中统一管理,各组件分别获取

4. Router

4.1. vue-router路由的两种模式

vue-router中默认使用的是hash模式

  1. hash模式, 带#。如:http://localhost:8080/#/pageA。改变hash,浏览器本身不会有任何请求服务器动作的,但是页面状态和url已经关联起来了。
  2. history模式,不带#, 如:http://localhost:8080/ 正常的而路径,并没有#。基于HTML5的 pushState、replaceState实现

4.2. vue-router如何定义嵌套路由

通过children 数组:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const router = new VueRouter({
routes: [
{
path: "/parentPage",
component: testPage,
children: [
{
path: "/childrenA",
component: childrenComponentA,
},
{
path: "/childrenB",
component: childrenComponentB,
},
],
},
{
// 其他和parentPage平级的路由
},
],
});

4.3. vue-router有哪几种导航钩子?

  1. 全局导航钩子:router.beforeEach(to,from,next)
  2. 组件内的钩子beforeRouteEnter (to, from, next) beforeRouteUpdate (to, from, next) beforeRouteLeave (to, from, next)
  3. 单独路由独享组件 beforeEnter: (to, from, next)

4.4. $route和$router的区别

  1. $route是“路由信息对象”,包括path,params,hash,query,fullPath,matched,name等路由信息参数。
  2. $router是“路由实例”对象包括了路由的跳转方法,钩子函数等

4.5. 路由之间跳转的方式

  1. 声明式(标签跳转)
  2. 编程式( js跳转)

4.6. active-class是哪个组件的属性

vue-router 模块 的router-link组件

环境:

  • React 17.x
  • react-router-dom: 5.2

1. 概述

React 本身是一个极简的类库,并且遵循渐进式原则,所以是不带路由(Router)功能的。对于稍复杂些的应用,没有路由显然是不可以的,所以就需要引入路由(React Router)库。

React Router 从5.0开始只分为Core,Web 和Native3种。 从5.0开始,彻底将原本的针对网页使用的react-router的npm package命名改为了react-router-dom。也就是说,针对web应用,用react-router-dom吧。(本文暂不涉及Native)

官方文档: https://reacttraining.com/react-router/

BrowserRouter与HashRouter的区别

React Router 有2中模式,BrowserRouter与HashRouter,下面我们来看一下区别

  1. url表现形式不一样,看是否包含#
  1. 底层原理不一样
  • BrowserRouter使用的是HTML5的history API(window.history.pushState, popState)
  • HashRouter使用的是URL的哈希值。
  1. 刷新后对路由state参数的影响
  • BrowserRouter没有任何影响,因为state保存在history对象中。
  • HashRouter刷新后会导致路由state参数的丢失。

安装和使用

  1. 安装:
    npm i react-router-dom

  2. 简单使用,
    参考:https://reactrouter.com/web/guides/quick-start

环境:

  • Angular: 8+

1. 为什么要优化

双向绑定是一柄双刃剑,提高开发效率的同时,也牺牲了性能。当然,随着硬件性能的提升,Angular自身性能的提升,对于一般(中小)复杂度的应用,性能问题可以忽略不计。但是对于特殊场景,或复杂页面来说,我们就需要单独的处理数据绑定问题,否则就会有卡顿的现象,影响用户体验。

2. 编程习惯方面

平时的一些小技巧,小习惯,都可以改善Angular绑定方面的性能。

2.1. NgForOf,加入trackBy提升性能

trackBy定义如何跟踪可迭代项的更改的函数。在迭代器中添加、移动或删除条目时,指令必须重新渲染适当的 DOM 节点。为了最大程度地减少 DOM 中的搅动,仅重新渲染已更改的节点。

默认情况下,变更检测器假定对象实例标识可迭代对象。提供此函数后,指令将使用调用此函数的结果来标识项节点,而不是对象本身的标识。

2.2. Angular数据绑定的三种方式

1
2
3
4
5
<div>
<span>Name {{item.name}}</span> <!-- 1. 直接绑定 -->
<span>Classes {{item | classPipe}}</span><!-- 2. pipe方式-->
<span>Classes {{classes(item)}}</span><!-- 3.绑定方法调用的结果 -->
</div>
  1. 直接绑定: 大多数情况下,这都是性能最好的方式。
  2. 绑定方法调用的结果:在每个脏值检测过程中,classes方程都要被调用一遍。如果没有特殊需求,应尽量避免这种使用方式。
  3. pipe方式: 它和绑定function类似,每次脏值检测classPipe都会被调用。不过Angular给pipe做了优化,加了缓存,如果item和上次相等,则直接返回结果。
1
<li *ngFor="let item of items; index as i; trackBy: trackByFn">...</li>

2.3. 除非需要,都是用单向绑定,减少监控值的个数

对于一般数据来说,都是只需要展示给用户,不需要修改。那么对于这部分数据,使用单向绑定即可(ts->html).
如:

1
2
<!-- 也称插值绑定 -->
<span>{{yourMessage}}</span>

3. ChangeDetectionStrategy.OnPush 进行性能提升

对于一些很复杂的页面,上面的小技巧就不够用了,不过Angular也是考虑到这些了,提供了不少方法。
Angular 对比 AngularJS 在变化检测上由原来的双向检测(父->子,子->父)变为了单向(父->子)。所以每一次变化检测都会确定性地收敛。
Angular定义一个组件时,可以传入一个变化检测配置项为

1
changeDetection: ChangeDetectionStrategy.OnPush | ChangeDetectionStrategy.Default;

onpush策略只判断输入的引用(如果是object)是否改变,来判断是否进行脏检查。因此,我们可以使用onpush策略来减少变化检测的开销。

4. 利用ngzone-runOutsideAngular优化

Angular依赖NgZone来监听异步操作,并从根部执行变化检测。换句话说,我们代码中的每一个 addEventListener都会触发脏检查。但是如果我们非常明确,有些addEventListener要执行的东西,不会(或者说可以忽略)影响数据结果,不想然他触发脏检查。比如监测scroll,监测鼠标事件等。

针对这种情况, 我们可以使用zone提供的runOutsideAngular,让这些事件不触发脏检查。

1
2
3
this.zone.runOutsideAngular(() => {
window.document.addEventListener('mousemove', this.bindMouse);
});

5. 手动控制脏检查 ChangeDetectorRef

Angular的ChangeDetectorRef实例上提供了可以绑定或解绑某个组件脏检查的方法。

1
2
3
4
5
6
7
8
class ChangeDetectorRef {
markForCheck() : void // 通知框架进行变化检查/Change Detection
detach() : void // 禁止脏检查
detectChanges() : void // 手工触发脏检查, 从该组件到各个子组件执行一次变化检测
checkNoChanges() : void
reattach() : void // detach逆操作,启用脏检查
}

6. 总结

  1. 平时的一些小习惯,都可以提高angular的性能;
  2. 针对复杂应用,或者当出现卡顿时,我们也是有办法的!