JS's 100 classic interview questions (1) Just look at these four pieces, and you can take a sneak peek after collecting them

Young people, you don’t speak martial ethics, mouse tail juice~~~
Insert picture description here

The summary is to form your own js knowledge network, improve yourself, come on!

Start doing

1. Introduce the basic data types of js  
A: Undefined, Null, Boolean, Number, String

2. What built-in objects does js have?  
Answer: Data encapsulation objects : Object, Array, Boolean, Number, and String
  Other objects : Function, Arguments, Math, Date, RegExp, Error
  
3. The rationale for this object 
: this always points to the direct caller of the function (not Indirect caller);
  if there is the new keyword, this points to the object that came out of new;
  in the event, this points to the object that triggered the event, and in particular, this in the attachEvent in IE always points to the global object Window.
  You can look at my previous article this pointing to
  
4 and what does eval do  in different situations ?
Answer: Its function is to parse the corresponding string into JS code and run it;
  eval should be avoided, which is insecure and very performance-consuming (2 times, once parsed into js statements, once executed).
  You can use eval when converting a JSON string to a JSON object, var obj = eval('('+ str +')').

5. How to add, remove, move, copy, create and find nodes in the   DOM
Answer: // Create a new node
createDocumentFragment() // Create a DOM fragment
  createElement() // Create a specific element
  createTextNode() // Create one Text node
  // add, remove, replace, insert
  appendChild()
  removeChild()
  replaceChild()
  insertBefore() //Insert a new child node before the existing child node
  // Find
  getElementsByTagName() //By tag name
  getElementsByName() //Pass the value of the element's Name attribute (IE is more fault-tolerant and will get an array, including the id equal to the name value)
  getElementById() //Pass the element ID, uniqueness

6. What is the difference between null and undefined?
Answer: null is an object that represents "none", and is 0 when converted to a value; undefined is an original value that represents "none", and is NaN when converted to a value.
  undefined :
  (1) When the variable is declared but not assigned, it is equal to undefined.
  (2) When calling the function, the parameter that should be provided is not provided, and the parameter is equal to undefined.
  (3) The object has no attribute assigned, and the value of the attribute is undefined.
  (4) When the function has no return value, it returns undefined by default.
  null :
  (1) As a function parameter, it means that the function parameter is not an object.
  (2) As the end of the object prototype chain.
  
7. What exactly does the new operator do?
Answer:
  (1) Create an empty object, and the this variable refers to the object, and also inherits the function prototype.
  (2) Properties and methods are added to the object referenced by this.
  (3) The newly created object is referenced by this, and finally returns this implicitly.

8. What about JSON?
Answer:
  JSON (JavaScript Object Notation) is a lightweight data exchange format . It is based on a subset of JavaScript. The data format is simple, easy to read and write, and takes up little bandwidth.
  Format: Use key-value pairs , for example: {"age":"12", "name":"back"}

9. What is the difference and function of call() and apply()?
Answer: The
  apply() function has two parameters: the first parameter is the context, and the second parameter is an array of parameters. If the context is null, use the global object instead.
  Such as: function.apply(this,[1,2,3]);
  The first parameter of call() is the context, followed by the parameter sequence passed in by the instance.
  Such as: function.call(this,1,2,3);

10. How to obtain UA?
Answer:
  function whatBrowser() {   document.Browser.Name.value=navigator.appName;   document.Browser.Version.value=navigator.appVersion;   document.Browser.Code.value=navigator.appCodeName;   document.Browser.Agent.value =navigator.userAgent;   } 11. What common operations will cause memory leaks? Answer: A   memory leak means that any object still exists after you no longer own or need it.   The garbage collector scans objects periodically and counts the number of other objects that reference each object. If the number of references to an object is 0 (no other objects have referenced the object), or the only reference to the object is circular, then the memory of the object can be reclaimed.   Using a string instead of a function as the first parameter of setTimeout will cause a memory leak.   Closures, console logs, loops (when two objects refer to each other and retain each other, a loop will occur). 12. The difference between threads and processes Answer: A program has at least one process, and a process has at least one thread.   The division scale of threads is smaller than that of processes, which makes multithreaded programs have high concurrency.   In addition, the process has an independent memory unit during execution , and





  






  


  

Multiple threads share memory , which greatly improves the efficiency of the program.
  Threads are still different from processes during execution . Each independent thread has a program entry, sequential execution sequence, and program exit. However, threads cannot be executed independently, and must exist in the application program, and the application program provides multiple thread execution control.
  From a logical point of view, the meaning of multithreading is that in an application, multiple execution parts can be executed simultaneously . However, the operating system does not regard multiple threads as multiple independent applications to implement process scheduling and management and resource allocation. This is the important difference between process and thread.

13. How to solve the cross-domain problem
JSONP: The
principle is: dynamically insert the script tag, and introduce a js file through the script tag. After the js file is successfully loaded, the function we specify in the url parameter will be executed, and the json we need The data is passed in as a parameter.
Due to the limitation of the same-origin policy, XmlHttpRequest only allows to request resources from the current source (domain name, protocol, port). In order to achieve cross-domain requests, cross-domain requests can be realized through script tags, and then JSON data is output on the server and the callback function is executed. Thereby solving the cross-domain data request.
The advantage is that it is compatible, easy to use, and supports two-way communication between the browser and the server. The disadvantage is that only GET requests are supported.
JSONP: json+padding (inner padding), as the name implies, is to fill JSON into a box

<script>
    function createJs(sUrl){
    
    
        var oScript = document.createElement('script');
        oScript.type = 'text/javascript';
        oScript.src = sUrl;
        document.getElementsByTagName('head')[0].appendChild(oScript);
    }
    createJs('jsonp.js');

    box({
    
    
       'name': 'test'
    });

    function box(json){
    
    
        alert(json.name);
    }
</script>

14. Javascript garbage collection method

  • Labeled Clear (mark and sweep)
    This is the JavaScript most common form of garbage collection, when the variable into the execution environment, such as a function to declare a variable, the garbage collector to mark it as " into the environment ", when the variable leaving the environment when (End of function execution) Mark it as " Leave Environment ".
    The garbage collector will mark all the variables stored in the memory when it is running , and then remove the variables in the environment and the variables (closures) referenced by the variables in the environment. After these are completed, there is still a mark. Deleted variables
  • Reference counting (reference counting)
    often has memory leaks in lower versions of IE, most often because it uses reference counting for garbage collection. The strategy of reference counting is to track and record the number of times each value is used . When a variable is declared and a reference type is assigned to the variable, the number of references to the value is increased by 1, if the value of the variable becomes another , Then the number of references to this value is reduced by 1. When the number of references to this value becomes 0, it means that there is no variable in use and this value cannot be accessed. Therefore, the space occupied by it can be reclaimed so that the garbage collector will be in Clean up the space occupied by the value of 0 references when running.
    In IE, although JavaScript objects are garbage collected through mark removal, BOM and DOM objects are garbage collected through reference counting, which means that as long as BOM and DOM are involved, there will be circular references.

15. The idea of ​​quick sort and realize a quick sort?
The idea of ​​"quick sorting" is very simple. The entire sorting process only requires three steps:
  (1) Find a reference point in the data set
  (2) Create two arrays and store the left and right arrays respectively
  (3) Use recursion Compare next time

<script type="text/javascript">
        function quickSort(arr){
    
    
            if(arr.length<=1){
    
    
                return arr;//如果数组只有一个数,就直接返回;
            }
            var num = Math.floor(arr.length/2);//找到中间数的索引值,如果是浮点数,则向下取整
            var numValue = arr.splice(num,1);//找到中间数的值
            var left = [];
            var right = [];
            for(var i=0;i<arr.length;i++){
    
    
                if(arr[i]<numValue){
    
    
                    left.push(arr[i]);//基准点的左边的数传到左边数组
                }
                else{
    
    
                   right.push(arr[i]);//基准点的右边的数传到右边数组
                }
            }

            return quickSort(left).concat([numValue],quickSort(right));//递归不断重复比较
        }

        alert(quickSort([32,45,37,16,2,87]));//弹出“2,16,32,37,45,87”
    </script>

16. ES6 understands the
new template string (provides a simple string interpolation function for JavaScript), arrow function (the left side of the operator is the input parameter, and the right side is the operation and the returned value Inputs=>outputs. ), for-of (used to traverse data-such as the values ​​in an array.) The arguments object can be perfectly replaced by indefinite and default parameters. ES6 incorporates promise objects into the specification and provides native Promise objects. Added let and const commands to declare variables. Added block-level scope. The let command actually increases the block-level scope. ES6 stipulates that global variables declared by var commands and function commands are attributes of global objects; global variables declared by let commands, const commands, and class commands are not attributes of global objects. . There is also the introduction of the concept of module modules.

17. What design patterns have you used?
(1) Factory mode: The
main advantage is that the coupling between objects can be eliminated by using engineering methods instead of the new keyword. Concentrate all instantiated code in one place to prevent code duplication.
(2) The factory pattern solves the problem of repeated instantiation, but there is another problem, which is the identification problem, because it is impossible to figure out which object instance they are.


function createObject(name,age,profession){
    
    //集中实例化的函数var obj = new Object();
    obj.name = name;
    obj.age = age;
    obj.profession = profession;
    obj.move = function () {
    
    
        return this.name + ' at ' + this.age + ' engaged in ' + this.profession;
    };
    return obj;
}
var test1 = createObject('trigkit4',22,'programmer');//第一个实例var test2 = createObject('mike',25,'engineer');//第二个实例

(3) Constructor mode
Using the constructor method not only solves the problem of repeated instantiation, but also solves the problem of object recognition. The difference between this mode and the factory mode is that the
constructor method does not display the creation of objects (new Object());
directly assign properties and methods to this object;
there is no renturn statement.
(4) Prototype chain mode
(5) Combination mode of construction and prototype chain

18. Tell me about your understanding of
closures. The main purpose of using closures is to design private methods and variables . Closure advantage is to avoid contamination of global variables , the disadvantage is the closure will be permanent memory, increases memory usage, improper use is likely to cause a memory leak . In js, a function is a closure, and only a function can produce the concept of scope.
Closure has three characteristics :
(1) Function nested function
(2) The function can refer to external parameters and variables
(3) Parameters and variables are not Will be recycled by garbage collection

19. Please talk about the drawbacks of
cookies. Although cookies provide convenience for persisting client data and share the burden of server storage, they still have many limitations.
First: each specific domain name can generate up to 20 cookies
(1) IE6 or lower version can have up to 20 cookies
(2) IE7 and later versions can have 50 cookies at the end.
(3) Firefox has up to 50 cookies.
(4)
Chrome and Safari do not impose hard restrictions. IE and Opera will clear the least recently used cookies, and Firefox will randomly clear cookies.
The maximum cookie size is about 4096 bytes. For compatibility, generally it cannot exceed 4095 bytes.
IE provides a storage that can persist user data, called userdata, which has been supported since IE5.0. Each data is up to 128K, and each domain name is up to 1M. This persistent data is placed in the cache, and if the cache is not cleared, it will always exist.
Advantages: extremely high scalability and usability
Through good programming, control the size of the session object stored in the cookie.
Through encryption and secure transmission technology (SSL), the possibility of cookie cracking is reduced.
Only store insensitive data in cookies, even if it is stolen, there will be no major losses.
Control the lifetime of the cookie so that it will not be valid forever. The thief is likely to get an expired cookie.
Disadvantages:
Cookielimitation of quantity and length. Each domain can only have 20 cookies at most, and each cookie cannot exceed 4KB in length, otherwise it will be truncated.
Security issues. If the cookie is intercepted by someone, that person can get all the session information. Even encryption does not help, because the interceptor does not need to know the meaning of the cookie, he can achieve the goal by simply forwarding the cookie as it is.
Some states cannot be saved on the client. For example, in order to prevent repeated submission of forms, we need to save a counter on the server side. If we save this counter on the client side, it will have no effect.

20. Browser local storage
In higher versions of browsers, js provides sessionStorage and globalStorage. LocalStorage is provided in HTML5 to replace globalStorage.
Web Storage in html5 includes two storage methods: sessionStorage and localStorage .

sessionStorage is used to store data in a session locally. These data can only be accessed by pages in the same session and the data will be destroyed when the session ends. Therefore, sessionStorage is not a persistent local storage, but a session-level storage.

The localStorage for persistent local storage, unless the initiative to delete data, or the data is never out of date.

The difference between web storage and cookie The
concept of web storage is similar to cookie, the difference is that it is designed for larger storage capacity. The size of the cookie is limited, and every time you request a new page, the cookie will be sent, which invisibly wastes bandwidth. In addition, the cookie needs to specify the scope and cannot be called across domains.

In addition, Web Storage has methods such as setItem, getItem, removeItem, and clear . Unlike cookies, front-end developers need to encapsulate setCookie and getCookie.
But cookies are also indispensable: the role of cookies is to interact with the server and exist as part of the HTTP specification, while Web Storage is only for the purpose of "storing" data locally.
Browser support is not supported except for IE7 and below. In addition, other standard browsers are fully supported (ie and FF need to run in the web server). It is worth mentioning that IE always does good things. For example, userData in IE7 and IE6 is actually a solution for javascript local storage. Through simple code packaging, it can be unified that all browsers support web storage.
Both localStorage and sessionStorage have the same operation methods, such as setItem, getItem and removeItem, etc.

21. The difference between cookie and session:
(1) Cookie data is stored on the client's browser, while session data is stored on the server.
(2) Cookies are not very secure. Others can analyze the cookies stored locally and perform cookie spoofing. In consideration of safety, session should be used.
(3) The session will be saved on the server for a certain period of time. When the number of visits increases, it will take up the performance of your server.
To reduce server performance, cookies should be used.
(4) The data saved by a single cookie cannot exceed 4K. Many browsers limit a site to save a maximum of 20 cookies.
(5) So personal suggestion:
store important information such as login information as SESSION.
Other information can be stored in COOKIE if it needs to be kept.

22. How to realize the communication between multiple tabs in the browser?
Call local storage methods such as localstorge and cookies

23. What are the ways of js delay loading?
Defer and async, dynamically create DOM (create script, insert into DOM, callBack after loading), load js asynchronously on demand.

24. List the different features of IE and other browsers?
(1) IE supports currentStyle, FIrefox uses getComputStyle
(2) IE uses innerText, Firefox uses textContent
(3) Filter aspect: IE:filter:alpha(opacity=num); Firefox: -moz-opacity:num
(4) Event Aspect: IE: attachEvent: Firefox is addEventListener
(5) Mouse position: IE is event.clientX; Firefox is event.pageX
(6) IE uses event.srcElement; Firefox uses event.target
(7) IE only eliminates the origin of the list Need margin:0 to achieve the final effect; FIrefox needs to set margin:0;padding:0 and list-style:none
(8) CSS rounded corners: rounded corners are not supported under ie7

25. Several ways to create javascript objects
(1) Factory mode
(2) Constructor mode
(3) Prototype mode
(4) Mixed constructor and prototype mode
(5) Dynamic prototype mode
(6) Parasitic constructor mode
(7) Safe Constructor Mode

The follow-up is still being updated~~~

Guess you like

Origin blog.csdn.net/qq_43291759/article/details/109746828