The purpose of this article is to record the interview questions encountered in the interview, including js common, easy to mistake, important knowledge points

The difference between window.onload and document.ready

Window. onload is the loading of all elements in the page, including images. Document. ready is when the document structure is loaded, but does not contain images, other media files; $(function(){}) and $(document).ready(function(){}). Window.onload is executed after the DOM tree is loaded and all files are loaded, so it is slower than document.ready.Copy the code

Array to heavy

var arr = ['a','bb','22','a','yuci','haha','22']; Copy the code
  1. Es6’s set() method
var unique = new Set(arr);  
console.log(Array.from(unique)); Copy the code
  1. Use the push ()
var arr2 = []; for(var i = 0; i < arr.length; {if i++) {(function (I) (arr2. IndexOf (arr) [I] = = 1) {/ / does not contain a value is returned - 1 arr2. Push (arr [I]); } }(i)) } console.log(arr2);Copy the code
// If the first occurrence of the i-th item in the current array is not I, then the i-th item is repeated and ignored. Var arr3 = [arr[0]]; for(var i = 1; i < arr.length; i++) { (function(i) { if(arr.indexOf(arr[i]) == i) { arr3.push(arr[i]); } }(i)) } console.log(arr3);Copy the code
  1. Sort to remove adjacent duplicate elements
var arrSort = arr.sort(); var arr4 = []; for(let i = 0; i< arrSort.length; i++) { if(arrSort[i] ! = arrSort[i+1]) { arr4.push(arrSort[i]); } } console.log(arr4);Copy the code
  1. Use the splice ()
var len = arr.length;  
for(let i = 0; i < len; i++) {  
    for(let j = i + 1; j < len; j++) {  
        if(arr[i] === arr[j]) {  
            arr.splice(i,1);  
            len--;  
            j--;  
        }  
    }  
}  
console.log(arr); Copy the code

Event delegation

Thanks to event bubbling, when multiple elements have the same event, bind the event to the parent element

var oUl = document.getElementById('oul'); oUl.addEventListener('click', function(e) { var e = e||window.event; var tar = e.target; if(tar.nodeName === 'LI') { alert(tar.innerHTML); }})Copy the code

For more details, see:Event delegation

Judge variable types

Typeof () is used to judge simple data;

Whether a variable is an Object or array using instanceof, constructor or Object. The prototype. ToString. Call ();Copy the code

For more details, see: Determine the data type

Synchronous and asynchronous (Brief Description)

Synchronization: Due to the single js thread, the synchronization tasks are queued to be executed on the main thread. If the previous tasks are not completed, the subsequent tasks will always wait. Asynchronous: Does not enter the main thread, but enters the task queue and waits for the main thread task to complete. The most basic asynchronous operations, setTimeout and setInterval, wait for the main thread task to finish, and then execute the inside function.Copy the code

For more details, see:Js runtime mechanism

Several cases where false is returned

False, null, 0, “”, undefined, NaN

Js type values

Storage: Simple data types: Stored on a stack; Reference data types: stored in the heap, stored in the stack pointer to the address stored in the heap, the interpreter will first retrieve the address in the stack, from the heap entity; Size: Simple data type: fixed size, small footprint, frequent use, so stored in the stack; Reference data type: the size is not fixed and occupies large space.Copy the code

closure

What is a closure: a function that has access to variables in another scope. How to solve it?Copy the code
for(var i = 0; i < 10; i++) {  
    setTimeout(function() {  
        console.log(i);    
    }, 1000);  
}  Copy the code

Function (){console.log(I); function(){console.log(I); function(){console.log(I); }, at the end of the loop I becomes 10, so the output is all 10;

Use closures to self-execute anonymous function wraps:

for(var i = 0; i < 10; i++) {  
    (function(j) {  
        setTimeout(function() {  
            console.log(j);    
        }, 1000);  
    })(i);  
} Copy the code

The external anonymous function executes immediately, takes I as an argument, and assigns a value to j, because it executes immediately, so it prints a different value each time.

References to outer variables are not recycled, which consumes more memory than other functions and may cause memory leaks.

This point

Global scope: point to window (in strict mode there is no global variable, point to undefined); Normal function calls: point to window; Object method call: refers to the object that last called it; Constructor calls: point to objects coming out of new; The display sets this: call, and the apply method shows that this points to the object specified by the first argumentCopy the code

What exactly does New do

Create a new object foo; __proto__ = foo. Prototype; Dynamically refer this to a new object, foo.apply (Foo, arguments); Execute the code in the function body; Put back the new object foo;Copy the code

Prototype and prototype chain

Creating a function creates a Prototype property for it that points to the function’s prototype object, which automatically gets the constructor property pointing to the function whose Prototype property belongs.

Function.prototype.a = "a"; Object.prototype.b = "b"; function Person(){} console.log(Person); //function Person() let p = new Person(); console.log(p); //Person {} object console.log(p.a); //undefined console.log(p.b); //bCopy the code
P. __proto__ = = = Person. The prototype; Person.prototype.constructor === PersonCopy the code

When calling a method or find some attributes, first in itself may call and search, if its not this property or method, will go to its __proto__ attribute is called for, it is also the constructor’s prototype call lookup, if also does not have the property of the constructor method, will go to the constructor the prototype of implicit search, All the way to NULL, and that’s the prototype chain.

For more on the prototype see:Prototype and prototype chain

Inheritance way

Prototype chain inheritance:

The prototype of Child() inherits the method properties of Parent() as an instance of Parent()

Because all instances inherit stereotype method properties, when one instance changes the stereotype property value, all instances call that property value

function Parent() {}  
Parent.prototype.parentSay = function() {  
    return 'i am parent';  
}  
function Child() {}  
Child.prototype.childSay = function() {  
    return 'i am child';  
}  
Child.prototype = new Parent();  
var par = new Parent();  
var kid = new Child();  
  
console.log(kid.parentSay());           //i am parent Copy the code

Constructor inheritance:

The superclass constructor is called inside the subclass constructor by call or apply

Function reuse is not possible

function People() {  
    this.name = ['zhangsan','lisi','wangwu'];  
}  
function Person() {  
    People.call(this);  
}  
var per1 = new Person();  
per1.name.push('zhanliu');  
console.log(per1.name);     //["zhangsan", "lisi", "wangwu", "zhanliu"]  
  
var per2 = new Person();  
console.log(per2.name);     //["zhangsan", "lisi", "wangwu"]  Copy the code

Combinatorial inheritance:

The most common inheritance pattern is to combine stereotype chain inheritance with constructor inheritance

Stereotype chains inherit shared properties and methods, and constructors inherit instance properties

function People(num) { this.num = num; this.name = ['zhangsan','lisi','wangwu']; } People.prototype.numCount = function() { console.log(this.num); } function Person(num) { People.call(this, num); } Person. Prototype = new People(); Person.prototype.constructor = Person; var per1 = new Person(10); per1.name.push('zhaoliu'); console.log(per1.name); //["zhangsan", "lisi", "wangwu", "zhanliu"] per1.numCount(); //10 var per2 = new Person(20); console.log(per2.name); //["zhangsan", "lisi", "wangwu"] per2.numCount(); / / 20Copy the code

For more inheritance methods, see:Inheritance way

Common methods for arrays

Change the original array:

Remove pop() from tail, add push() to tail, remove shift() from head, add unshift() to head, sort sort(), reverse array element (), remove or insert element splice();Copy the code

Does not change the group of elements:

Concatenate array elements join(), slice(), indexOf(), lastIndexOf(), toString()Copy the code

For a more detailed summary of array methods, see:Array Array method summary

Data is stored

Cookie: used for client and server communication, also has the function of localStorage localStorage, sessionStorage: dedicated for storage difference: size: Cookie capacity is 4K, because used for client and server communication, all HTTP are carried, if too large to reduce efficiency; LocalStorage, sessionStorage the size is 5M. Expiration time: Cookies will be deleted when the browser is closed, unless the deletion time is actively set; LocalStorage continues to exist until the user removes or clears the browser cache; SessionStorage deleted when the browser is closed.Copy the code

Conclusion:

If there are any mistakes, please correct them