JS interview stereotyped essay knowledge summary (latest)

Article directory


The following are 40 common JS interview questions, let's start rushing!

1. JS data type

undefined、symbol、string、number、null、boolean、bigInt、object

1. Kind

  • 7 original (basic) data types: number, string, boolean, null, undefined, symbol, bigInt (stored in the stack, fixed size)
  • Reference (complex) data types: object, array, function (stored in the heap, size is not fixed)
    2. Concept
  • Basic: A simple data segment, representing a basic type that cannot be further subdivided
  • Complicated: an object composed of two values ​​is a container for storing multiple attributes, and the object is worth storing as a reference address, and manipulating the corresponding value will change the value 3.
    Memory
  • Basic: The original data type is characterized by small space occupation and fixed size. It belongs to frequently used data and is stored in the stack area in memory.
  • Complexity: The complex data type is characterized by occupying a large space and its size is not fixed. Only storing in the stack in the memory will affect the running of the program, so the stack area + heap area used in the memory, the stack area stores the pointer, the pointer is the memory address pointing to the entity, and the entity is stored in the heap to supplement in the
    operating
    system The memory is divided into:
  • Stack area: the compiler automatically allocates and stores parameter variables (a stack similar to a data structure)
  • Heap area: allocated by the developer, if not actively released, it will be recovered after the end of the program

Second, the method of judging the data type

1.typeof

  • Generally used to judge the basic data type ,
  • Currently, it can return string, number, boolean, symbol, bigint, unfined, object, and function, which are eight judgment types, but note that null and arrays return Object. And for reference types, object is returned because the prototype of all objects is ultimately Object.
  • Interview question: Why is typeof null Object?
  • Answer: Because in JavaScript, different objects are stored in binary . If the first three digits of the binary are all 0 , the system will judge it as an Object type, and if the binary of null is all 0, it will naturally be judged as an Object
    supplement
    . This bug is left in the original version of JavaScript, expand the other five flags:
  • 000 objects
  • 1 integer
  • 010 double precision type
  • 100 strings
  • 110 Boolean type

2. instanceof (judged according to the prototype chain)

  • If the reference data type is judged, the basic data type is judged to be invalid
  • instanceof can also determine whether an instance is its parent type or ancestor type
  • The principle of instanceof is actually to find the prototype chain of the target object (judging whether the prototype attribute of the constructor appears on the prototype chain of an instance object, and the end of the prototype chain is null)
[] instanceof Array ; //true

Handwritten implementation of instanceof

function myInstance(L,R){
    
    
//获取判断对象隐式原型
var LP = L._proto_
//判断类型的显示原型
var RP = R.prototype
while(true){
    
    
if(LP == null) return false
if(LP == RP) return true
LP = LP._proto_
}
console.log(myIntance({
    
    },object))
}

3. Object constructor: constructor

  • Similar to instanceof, but instanceof can only detect reference types, and constructor can also detect basic types, because constructor is a property of a prototype object pointing to a constructor.
    Notice
  • Null and undefined are invalid objects, so there will be no constructor, so it cannot be judged based on the constructor.
  • The constructor of JS objects is unstable. This is mainly reflected in custom objects. When the developer rewrites the prototype, the original constructor will be lost, and the constructor will default to Object
  • Class inheritance will also cause errors, because Object is overwritten, and the detection result will be wrong

4. Object prototype chain judgment: Object.prototype.toString.call

  • toString is a method on the Object prototype object. This method returns the specific type of its caller by default. More strictly speaking, it is the object type pointed to by this when toString is running. The format of the returned type is [object,xxx], and xxx is the specific type Data types, including: String, Number, Boolean, Undefined, Null, Function, Date, Array, RegExp, Error, HTMLDocument... Basically all object types can be obtained through this method.
  • It must be obtained through Object.prototype.toString.call, not directly new Date().toString(). From the perspective of the prototype chain, the prototype chain of all objects eventually points to Object. According to the JS variable search rules, other objects It should also be possible to directly access the toString method of Object, but in fact, most objects have implemented their own toString method, which may cause the toString of Object to be terminated, so it is necessary to use call to enforce the toString method of Object .
  • Disadvantages: cannot be subdivided into instances of so-and-so
1	Object.prototype.toString.call("a")
	"[object String]"
2	Object.prototype.toString.call(undefined)
	"[object Undefined]"
3	Object.prototype.toString.call(null)
	"[object Null]"
4	Object.prototype.toString.call(new Date())
	"[object Date]"

3. What exactly does the new operator do?

The instance created by the new operator through the constructor can access the properties and methods of the constructor, and also connect the instance and the constructor through the prototype chain

1.创建一个新对象,并且在内存中创建一个新的地址
let obj = new Obect()
2.设置创建对象的原型链继承构造函数的原型
obj._proto_ = 构造函数的.prototype
3.绑定构造函数的this的指向,将构造函数的this指向创建的对象,并且执行函数体
 let result =Fn.call(创建的对象);
4.判断构造函数的返回值类型,如果是值类型,返回创建的对象。如果是引用类型,就返回这个引用类型的对象
return result instanceof Object? result: obj;

3. The difference between dom.onclick and dom.addEventListener?

1. Basic concepts

  • dom.onclick: The onclick event will occur when the element is clicked. It can be used in HTML and JavaScript. All browsers support the onclick event.
  • dom.addEventListener: The document.addEventListener() method is used to add events to an element. It has three parameters, which are the event, the callback function that triggers the execution, and whether it is executed in the capture or bubbling phase. IE8 and the old versions before IE8 do not support it. In the past, the attachEvent() method was used to monitor the binding method

2. Main difference

dom.onclick:

  • You can listen to events on inline tags, but you can only add one event, and binding multiple latter events will overwrite the former
  • Potential security issues XXS cross-site scripting attack
  • Cannot select DOM event stream
  • Do not separate document structure and logic when inlining

dom.addEventListener

  • Regardless of performance, you can add multiple events bound to calcium elements and they will execute
  • Can no longer be used in HTML tags, only in script
  • The event stream can be selected through the useCpature parameter
  • Separate document structure, easier to maintain in large projects

Fourth, JS built-in properties and methods

Built-in objects commonly used in JS: Array object, Date object, regular expression object, string object, Global object Methods
:
Some methods of these built-in objects
Details of each method

Five, logical and && and logical or ||

Belongs to short-circuit operators (e.g. the first operand determines the result, the second operand is not evaluated)

  • As long as "&&" is false before, no matter whether "&&" is followed by true or false, the result will return the value before "&&";
  • As long as "&&" is preceded by true, no matter whether "&&" is followed by true or false, the result will return the value after "&&";
  • As long as "||" is false before, regardless of whether "||" is true or false, the value after "||" will be returned.
  • As long as "||" is true before, regardless of whether "||" is true or false, it will return the value before "||".

Replenish

  • True value: all values ​​are true except false
  • 6 false values: " ", false, undefined, null, NaN, 0 will be converted to false in logical operations and implicit conversions

6. Scope and scope chain

scope

  • The accessible scope of variables and functions, that is, the scope controls the visibility and life cycle of this variable
  • Global scope: Variables and functions can be accessed throughout the whole world, and its life cycle is equivalent to that of the page life cycle
  • Local scope: functions, variables and functions declared inside {}

scope chain

Different scopes between the upper and lower levels form the scope chain

  • When looking for the value and method of a variable, if it cannot be found in the current scope (inside itself), it will go to its upper level to find out if there is any, until there is no global one, and return undefined.
  • The internal function accesses the external function function variable is to take the scope chain search

7. Pre-parsing and variable promotion

When the JS engine executes the code 1. Pre-parsing 2. Executing code
pre-parsing : The JS engine promotes all JS variables declared with Var and global functions to the front of the scope. Variable
promotion : promotes all variable declarations to The front of the current scope, no assignment operation

8. Three methods of changing the function pointed to by this (bind / call / apply)

The function is used to redefine this object!

  • The same: both can change the direction of this, and they are all mounted on Function.prototype
  • The difference: call and apply are executed immediately after use, while bind returns a new function, and the target function will be executed only after calling the callback function. And the format of the parameters of call and bind is the same, the first parameter is the object pointed to by this , the other parameters use commas , apply means that the parameters need to be put into the array .
//调用父级的同时将父级函数里面的this指向子函数里面的this,使子函数可使用父函数的里面的方法和属性
father.myFun.call(son,'成都','上海');    
father.myFun.apply(son,['成都','上海']);       
father.myFun.bind(son,'成都','上海')();  

Nine... What is the difference between the args remaining parameter (spread operator) and the arguments object?

1. The remaining parameters (expansion operator) only include those actual parameters that have no corresponding formal parameters, while arguments (corresponding to the array-like object passed to the function parameters) includes all the actual parameters passed to the function.
2. The arguments object is not a real array, but the remaining parameters are real Array instances, which means you can use all array methods directly on it, such as sort, map, forEach or pop.
3. The arguments object also has some additional attributes such as the callee attribute).

Ten, traversal method

Details: http://t.csdn.cn/xe0dd
1. The method of traversing the array

  • 1. for loop - use variables to cache the length of the array
  • 2. forEach() - ES5 syntax, execute the provided function once for each element of the array, break and return cannot be used

arr.forEach(function(item,index,arr){
    
    
	console.log("元素:"+item+" 索引:"+index+" 整个数组:"+arr);
  • 3.map() --ES5 syntax, creating a new array, the result is the result returned after calling a provided function for each element in the array
arr.map(function(val,index){
    
    
	console.log("元素:"+val+" 索引:"+index);
	return val*val;

  • 4.for of (iterable objects can be traversed)

for(let item of arr){
    
    
	console.log("元素:"+item);

Second, the method of traversing objects

  • 1.for...in traverses an object's own, inherited, enumerable, and non-Symbol attribute names in any order. For each different attribute, the statement will be executed
let obj1 = {
    
    
            a:"A",
            b:"B",
            c:"C"
        }
        for(let ch in obj1){
    
    
           console.log(ch); a b c
       }

If this method traverses the string,
let str = "abcdefj"
insert image description here

  • 2.Object.keys() -- Returns an array composed of a given object's own enumerable property names , the order of the property names in the array is the same as that returned when using the for...in loop to traverse the object (the difference is that for- The in loop enumerates the properties in the prototype chain) in the same order
let obj1 = {
    
    
            a:"A",
            b:"B",
            c:"C"
        }
       console.log(Object.keys(obj1)); //(3) ['a', 'b', 'c']

If this method traverses the string,
let str = "abcdefj"
insert image description here

  • 3.Object.values() -- Returns an array of all enumerable property values ​​of a given object itself , in the same order as using the for...in loop
 let obj1 = {
    
    
            a:"A",
            b:"B",
            c:"C"
        }
       console.log(Object.values(obj1)); //(3) ['A', 'B', 'C']

If this method traverses the string,
let str = "abcdefj"
insert image description here

  • 4.Object.getOwnPropertyNames() -- Returns an array consisting of the property names of all the properties of the specified object (including non-enumerable properties but excluding properties with Symbol values ​​as names)
 let obj1 = {
    
    
            a:"A",
            b:"B",
            c:"C"
        }
       console.log(Object.getOwnPropertyNames(obj1)); //Array(3) ['a', 'b', 'c']

If this method traverses the string,
let str = "abcdefj"
insert image description here

Three, the method of traversing the string

  • for...of --ES6 syntax, can traverse iterable objects such as Array, Set, Map, String, TypedArray, arguments, etc., can use break, continue
  • for loop

11. JavaScript NaN property

The NaN property is a special value that represents a not-a-number value. This attribute is used to indicate that a value is not a number. A Number object can be set to this value to indicate that it is not a numeric value.

  • Features: Non-configurable, non-writable properties. But the value of this property can be changed in ES3
  • Features: NaN is a special value that is not equal to itself and is the only value that is not reflexive (reflexive, reflexive, that is, x = = = x does not hold). And NaN !== NaN is true.
  • Usage scenarios: 1. NaN is rarely used directly in coding. Usually when the calculation fails, it appears as the return value of a certain method of Math. 2. Use the isNaN() function to judge whether a value is a NaN value.
parseInt("blabla")typeof NaN; // "number"

Twelve, null and undefined?

Brief summary: undefined represents a value that does not exist (after a value is declared, if there is no assignment, the output will be undefined, which does not exist), and null represents no value (when we assign a value to null, then the output will be null, also It is empty and has no value.)

1. 
undefined == null //true, “==” 进行了隐式转换,undefined的值 是 null 派生来的,所以他们表面上是相等的
undefined === null //false
2. 
let a;
typeof a;//undefined

let b= null;
typeof b;//object
这里为什么typeof b 输出为 Object 呢?
答:null 不是一个对象,尽管 typeof age输出的是 Object,逻辑上讲, null 值表示一个空对象指针 ,这是一个历史遗留问题,JS 的最初版本中使用的是 32 位系统,为了性能考虑使用低位存储变量的类型信息,000 开头代表是对象,null表示为全零,所以将它错误的判断为 Object 。

Thirteen, the difference between = = = and = =

The main difference: when comparing == , if the types are not equal, they will be converted to the same type first, and then compare the values. But === will not, it can only compare values ​​under the same type , and will not do type conversion. There is also = , which is an assignment, not an operator.
1. = = =
The following rules are used to judge whether two values ​​=== equal:

  • Not equal if types are different
  • Equal if both are numeric and have the same value; except that they are not equal if at least one of them is NaN. (To judge whether a value is NaN, you can only use isNaN() to judge)
  • If both are strings with the same character at each position, they are equal; otherwise, they are not equal.
  • Equal if both values ​​are true, or both false.
  • If both values ​​refer to the same object or function, then they are equal; otherwise, they are not equal.
  • If both values ​​are null, or both are undefined, then equal.
    2.==
  • If two values ​​are of the same type, a === comparison is performed.
  • If two values ​​are of different types, they may be equal. Perform type conversion and comparison according to the following rules:
  • If one is null and the other is undefined, then equal.
  • If one is a string and the other is a value, convert the string to a value before comparing.
  • If any value is true, convert it to 1 and compare; if any value is false, convert it to 0 and compare.
  • If one is an object and the other is a number or string, convert the object to a value of the underlying type and compare. Objects are converted to underlying types, -
  • Use its toString or valueOf method. js core built-in class, will try valueOf before toString;
  • Any other combination is not equal.

14. Why is 0.1+0.2 not equal to 0.3?

console.log(0.1 + 0.2)  // 结果是0.30000000000000004,而不是3
  • In JavaScript, numbers are stored using the IEEE 754 double precision standard. For example, the decimal is represented by a fixed length of 64 bits, of which 1 bit represents the sign bit, 11 bits are used to represent the exponent bit, and the remaining 52 mantissa bits.
  • Among them, for example, the conversion of 0.1 to binary is an infinite loop number, which will exceed 52 bits, which will lead to lack of precision, so 0.1 can only be stored as an approximate value in the computer
  • 0.1+0.2 will be converted to binary first, then added and stored, and finally converted to decimal when taken out, and this value is not close to 0.3, so unequal results will appear.
  • Solution: Convert floating point numbers to integers for calculation

15. JS language type

JavaScript is a weakly typed, dynamic language.

  • Operations that convert secretly are often called implicit type conversions. A language that supports implicit type conversion is called a weakly typed language, and a language that does not support implicit type conversion is called a strongly typed language.
  • There is no need to define the variable type before declaring the variable. We call this kind of dynamic language that does not need to confirm the data type of its variables before using it.

16. Date and time format conversion in JavaScript && encapsulates a countdown function

datetime format conversion

声明实例化构造函数
var date = new Date()
时间戳:
var nowDate = date.getTime()  //返回从1970年到现在的毫秒数
let timestamp =(new Date()).valueOf();//返回从1970年到现在的毫秒数
        var year = date.getFullYear() //获取年
        var month = date.getMonth() + 1 //获取月 (0 ~ 11)
        var day = date.getDate() //获取天(1-31)
        var hours = date.getHours() //获取小时 (0 ~ 23)
        var m = date.getMinutes()//获取分(0 ~ 59)
        var s = date.getSeconds()//获取秒(0 ~ 59)
        month < 10 ? month = "0" +month : month
        day < 10 ? day = "0"+day : day
        hours < 10 ? hours = "0" + hours : hours
        m < 10 ? m = "0" + m : m
        s < 10 ? s = "0" + s : s
        
        var nowDate = year + "年" + month + "月" + day + "日" +hours+"时"+ m + "分"+ s + "秒"
        console.log(nowDate)

countdown function

   function countDown(time) {
    
    
 			//前面添加+ 返回的格式就是毫秒数 否则Sun May 01 2022 21:40:47 格式
            let nowTime = +new Date(); //返回的是现在的总毫秒数
            let inputTime = +new Date(time);//返回的是用户输入的总毫秒数
            // 1000 将毫秒数转换为秒数
            let times = (inputTime - nowTime) / 1000;
            // 分- 时 - 天
            let d = parseInt(times / 60 / 60 / 24);  
            d = d < 10 ? '0' + d : d;
            //分-时 - 余数(一天24小时余下的那个数)
            let h = parseInt(times / 60 / 60 % 24); 
            h = h < 10 ? '0' + h : h;
            // 分 - 余数
            let m = parseInt(times / 60 % 60 ); 
            m = m < 10 ? '0' + m : m;
            //余数
            let s = parseInt(times % 60); 
            s = s < 10 ? '0' + s : s;
            return d + '天' + h + '时' + m + "分" + s + '秒';
        }
        //输入的时间一定比现在的时间大,因为是倒计时
        console.log(countDown('2022-6-1 18:00:00'));

17. What is the length of the function?

length is an attribute value of the function object, which refers to how many parameters the function must pass in, that is, the number of formal parameters. The number of formal parameters does not include the number of remaining parameters, only the number of parameters before the first one with a default value.
How many formal parameters does a general function have, and the length is how many

function fn1 () {
    
    }
function fn2 (name) {
    
    }
function fn3 (name, age) {
    
    }

console.log(fn1.length) // 0 
console.log(fn2.length) // 1 
console.log(fn3.length) // 2

If there are default parameters

function fn1 (name) {
    
    } 
function fn2 (name = '林三心') {
    
    } 
function fn3 (name, age = 22) {
    
    } 
function fn4 (name, aaa, age = 22, gender) {
    
    } 
function fn5(name = '林三心', age, gender, aaa) {
    
    } 

console.log(fn1.length) // 1 
console.log(fn2.length) // 0 
console.log(fn3.length) // 1 
console.log(fn4.length) // 2
console.log(fn5.length) // 0

Remaining parameters
The remaining parameters are not included in the calculation of length

function fn1(name, ...args) {
    
    } 
console.log(fn1.length) // 1

18. DOM event flow

Three elements of the event : event source (processing object), binding event, adding event handler
event flow:

  • Capture phase: the process of searching for the target element propagation step by step from the topmost window of the DOM, and passing down the captured event when it encounters the binding
  • Target stage: reaching the target stage triggers the binding event
  • Bubbling stage: the event starts to be received by specific elements, and propagates upwards to the DOM to the top-level window step by step. What events support
    bubbling ? Mouse events, keyboard events, and click events support bubbling click, dbclick, keydown, keyup , mousedown, mousemove, mouseout, scroll and focus and defocus events, loading events, ui events, mouse move in and out events are not supported. mouseenter, mouseleave event object event




// 兼容性问题8后都不支持
         //系统自动创建,不需要传递参数
        var div = document.querySelector('div')
         //系统自动创建,不需要传递参数
        div.addEventListener('click',function(event){
    
    
            // 都是div 两者之间的区别
            console.log(event.target); //div 触发事件的元素(那个元素点击)
            console.log(this); //div 绑定事件的元素(哪个元素绑定)
            event.cancelBubble  // 阻止事件冒泡  标准写法 event.propagation()
            event.preventDefault()  //阻止默认行为
        })

19. Constructor

In JavaScript, the function that instantiates an object through new is called a constructor, that is, an instance object is initialized, and the prototype property of the object inherits an instance object. The name of the constructor is generally capitalized~
The role of the constructor:

  • Creating objects: There are two ways to create objects in JavaScript, one is to build function + prototype, and the other is to use class.
    The execution process of the constructor
    The execution process of the constructor, the basic process of the new operator
1.创建一个新对象,并且在内存中创建一个新的地址
let obj = new Obect()
2.设置创建对象的原型链继承构造函数的原型
obj._proto_ = 构造函数的.prototype
3.绑定构造函数的this的指向,将构造函数的this指向创建的对象,并且执行函数体
 let result =Fn.call(创建的对象);
4.判断构造函数的返回值类型,如果是值类型,返回创建的对象。如果是引用类型,就返回这个引用类型的对象
return result instanceof Object? result: obj;

The instance created by the new operator through the constructor can access the properties and methods of the constructor, and the instance and the constructor are connected through the prototype chain.
The return value of the constructor In the constructor
, do not customize and explicitly return any value, the constructor will automatically return

  • Constructors try not to return values. Since returning a primitive value has no effect, returning an object renders the new operator useless.
    Replenish
  • In fact, in JavaScript,
  • let a = [] that is let a = new Array [];
  • function a () {} is let a = new Function () {}

20. Prototype and prototype chain

**Function: **Constructor and prototype prototype chain are for constructor and prototype to create objects (solve inheritance and memory consumption in JS)

构造函数的最主要问题在于,其定义的方法会在每一个实例上都创建一遍。
function Person(name) {
    
    
  this.name = name;
  this.age = 18;
  this.say = function () {
    
    
  	 console.log("你好,我今年" + this.age);
	}
}

let person1 = new Person("a");
let person2 = new Person("b");

console.log(person1.say == person2.say)  //false

**Solution:** Define the attribute or method on the prototype of the constructor, so that the created instance can find the method through the prototype search, and the methods owned by different instances are all methods on the prototype of the constructor (prototype The attributes and methods defined by the schema are shared by all instances)

function Person(name) {
    
    
  Person.prototype.name = name;
  Person.prototype.age = 18;
  Person.prototype.say = function () {
    
    
  	 console.log("你好,我今年" + this.age);
	}
}

let person1 = new Person("a");
let person2 = new Person("b");

console.log(person1.say == person2.say)  //true

**Reason:** As long as the constructor is created, it will have a prototype attribute pointing to its prototype object, and this prototype object also has a constructor attribute pointing to the function and characteristics of the constructor about the prototype and the prototype
chain

  • prototype attribute
    This attribute is unique to the constructor and is used to point to the prototype object of the constructor. Because of this point, the instances created in the constructor can share the attributes and methods in the constructor prototype
  • The constructor attribute
    The constructor attribute is located on the prototype object of the constructor and is used to point to the function that creates the object. Because all instances have access to the constructor, you can use the constructor property to verify the type of the prototype
  • inherit
  • We access a property of the instance or call a method, but it doesn't exist, then JavaScript tries to look it up in its prototype. Search layer by layer until the prototype of the final object found is null, then return. And if both have a property with the same name, the property on the instance will override the one on the prototype object.

21. What is the length of Chinese?

Chinese is stored in the database with two characters, but in the browser, since javascript is encoded in unicode, all characters are one for it, and the length of the Chinese is obtained instead of the length of the character

conlog.log("你好呀大笨蛋".length)  //6

This will lead to different verification lengths for Chinese at the front and back ends. How to solve it?

function getRealLength( str ) {
    
    
    return str.replace(/[^\x00-\xff]/g, '__').length; //这个把所有双字节的都给匹配进去了
}

22. Briefly describe the principle of cookie/session remembering login state mechanism

Session is the state saving mechanism of the server.
Cookie is the state saving mechanism of the client.
When accessing the server for the first time, the server will open up a space to store user information.
After each login, user information will be recorded in the session in key value format
. The server will store the sessionId (user information) in the cookie and return it to the visiting client. The
client will save the sessionID in the local cookie and record it on the corresponding website.
The next time it visits, it will carry the sessionId. The
server will verify the validity of the cookie. To determine whether the user is logged in

23. What is the difference between cookies, session, sessionStorage, and localStorage?

data cache

  • Store the data in the user's browser
  • Easy to set up, easy to read, and even refresh the page without losing data
  • Only strings can be stored, and the object JSON.stringify() can be encoded to store
    cookies
  • Located on the user's computer to maintain information on the user's computer until deleted by the user.
    session
  • Called session information, it is located on the web server and is mainly responsible for the interaction between the visitor and the website. When the visiting browser requests the http address, it will be passed to the web server and matched with the access information. When the website is closed, it means a session It's over, the website can't access the information, so it can't save permanent data, we can't access and disable the website
    sessionStorage data storage and get
  • The life cycle is to close the browser
  • Data under the same window can be shared
  • stored in the form of key-value pairs
  • sessionStorage.setItem(key,value)
  • sessionStorage.getItem(key)
  • sessionStorage.removeItem(key)
    localStorage data storage and acquisition
  • The life cycle is permanent, unless manually deleted, otherwise the closed page will also exist
  • Multiple windows can be shared (the same browser can be shared)
  • stored in the form of key-value pairs
  • localsStorage.setItem.(key,value)
  • localStorage.getItem(key)
  • localStorage.removeItem(key)
  • The differences between localStorage.clear()
    cookie and sessionStorage, localStorage are :
  • What they have in common: they are all saved on the browser side and have the same origin
  • the difference:
    • 1. The cookie data is always carried in the same-source http request (even if it is not needed), that is, the cookie is passed back and forth between the browser and the server, while sessionStorage and localStorage will not automatically send the data to the server, but only save it locally. Cookie data also has the concept of path (path), which can restrict cookies to only belong to a certain path
    • 2. The storage size limit is also different. The cookie data cannot exceed 4K. At the same time, because each http request will carry a cookie, the cookie is only suitable for saving small data, such as session identifiers. Although sessionStorage and localStorage also have storage size limitations, they are much larger than cookies and can reach 5M or greater
    • 3. The validity period of the data is different. sessionStorage: valid only before the current browser window is closed; localStorage: always valid, and saved even when the window or browser is closed, so it is used as persistent data; cookie: valid only before the set cookie expiration time, even if the window is closed or the browser is closed
    • 4. The scope is different, sessionStorage is not shared in different browser windows, even on the same page; localstorage is shared in all windows of the same origin; cookies are also shared in all windows of the same origin
    • 5. Web Storage supports an event notification mechanism, which can send notifications of data updates to listeners
    • 6. The api interface of web Storage is more convenient to use

24. charCodeAt() method

  • Returns the Unicode encoding of the first character of the string (the Unicode value of H): The charCodeAt() method can return the character at the specified position

  • Unicode encoding, the return value is an integer between 0 - 65535, representing the UTF-16 code unit at the given index. The position of the first character in the string is 0, the second character is 1, and so on.

25. The difference between for-in and for-of

The difference between the two:

  • 1. for-in just gets the index of the array; while for-of gets the value of the array

  • 2. for-in will traverse the entire prototype chain of the object, which has poor performance; while for-of only traverses the current object and will not traverse the prototype chain

  • 3. For array traversal, for-in will return all enumerable properties in the array (including enumerable properties on the prototype chain); for-of will only return the property value corresponding to the subscript of the array

  • 4. for-of is suitable for traversing collections with iterator objects such as arrays/strings/map/set, but cannot traverse ordinary objects (obj is not iterable)

  • 5. for-of only traverses the collection that currently has iterator objects, and does not traverse the prototype chain:

26. The event flow has three phases:

  1. Event capture phase: pass down from window to target element (parent to child), and trigger it when encountering a registered capture event during the process
  2. In the target phase: the event arrives at the target element, triggering the event registered on the target element
  3. Event bubbling phase: Pass up from the target element to the window (child to parent), and it will be triggered when a registered bubbling event is encountered during the process

27. Common events:

  1. Click event:
    1. onclick: click event
    2. ondblclick: double click event
2. 焦点事件
    1. onblur:失去焦点
    2. onfocus:元素获得焦点。

3. 加载事件:
    1. onload:一张页面或一幅图像完成加载。

4. 鼠标事件:
    1. onmousedown    鼠标按钮被按下。
    2. onmouseup    鼠标按键被松开。
    3. onmousemove    鼠标被移动。
    4. onmouseover    鼠标移到某元素之上。
    5. onmouseout    鼠标从某元素移开。
5. 键盘事件:
    1. onkeydown    某个键盘按键被按下。    
    2. onkeyup        某个键盘按键被松开。
    3. onkeypress    某个键盘按键被按下并松开。

6. 选择和改变
    1. onchange    域的内容被改变。
    2. onselect    文本被选中。

7. 表单事件:
    1. onsubmit    确认按钮被点击。
    2. onreset    重置按钮被点击。

JS common methods and built-in properties:

  • Object is an object that contains properties and methods, and can be a created object or an existing Document Object Model (DOM) object.
  • The return value of Object.keys(object) is an array containing the names of the object's enumerable properties and methods.
  • Array.filter(function) filters the array and returns the qualified array.

Twenty-eight, JS strict mode

Strict mode means that the js engine executes in strict mode. We only need to add "use strict" before the code or function to enable strict mode. Some restrictions are added to the execution of js code in strict mode, mainly to ensure that the code is executed in a safe environment and reduce unnecessary errors. In order to eliminate some imprecise, unreasonable, and unsafe places in js, it represents A more reasonable, safer, and more standardized development direction for js.
In strict mode, variables must be declared before they can be used.
In strict mode, this is undefined during precompilation;
in strict mode, arguments, caller, callee, and with are not supported; in
strict mode, repeated attributes and parameters are rejected; in
strict mode, local this must be assigned, and what is assigned is What.
In the this of the global execution context and in the function of the global execution context, this no longer points to the windon object.
It is not allowed to use undeclared variables. Object is also a variable.
It is not allowed to use the delete operator on variables or functions. It is not allowed to have
the same variable name.
It is not allowed to use octal.
It is forbidden to use the this keyword to point to the global object . It is not allowed to declare functions
inside if. Variables use the delete operator, throwing ReferenceError cannot assign values ​​to read-only properties of objects, cannot use delete operators on non-configurable properties of objects, and cannot add properties to non-expandable objects, both throw TypeError Object property names must be unique and cannot be found in functions Duplicate parameter





Modification of parameters inside the function will not be reflected in the arguments.
Arguments.callee and arguments.caller
cannot be declared inside the if function.
Abandon the with statement

Twenty-nine, ~~ characters

~~true == 1
~~false == 0
~~“” == 0
~~[] == 0

~~undefined ==0
~~!undefined == 1
~~null == 0
~~!null == 1
Which variables are useful for specific conversion:

Numerical strings can be converted to pure numbers
var a='123';
console.log(~~a); // Output 123
strings with other letters, symbols, or other things except numbers, all output Number type 0
var a='asd';

console.log(~~a); //Output 0

Any boolen type, if it is TRUE, it will output 1, and if FALSE, it will output 0;
var a=1==1;
console.log(~~a);//Output 1
special type, convert to Boolean is true output 1, convert Output 0 for boolean is false;
var a=undefined;

console.log(~~a);//output 0

var b=!undefined;

console.log(~~b);//output 1

Thirty, the difference between Map and object

details

  • Memory usage : Adding or deleting key/value pairs in batches depends on the engineering implementation of this type of memory allocation in each browser. It varies from browser to browser, but given a fixed size of memory, a Map can store about 50% more key/value pairs than an Object.
  • Insertion performance : Inserting new key/value pairs into Object and Map is about the same cost, though inserting into Map is generally slightly faster across all browsers. For both types, insertion speed does not scale linearly with the number of key/value pairs.If the code involves a lot of insertions
    , then obviously Map will perform better.
  • Lookup speed : Unlike insertion, the performance difference between looking up key/value pairs from a large Object and Map is minimal, but Object is sometimes faster if it contains only a few key/value pairs. In the case of using Object as an array (such as using consecutive integers as attributes), the browser engine can optimize and use a more efficient layout in memory. Lookup speed does not increase linearly with the number of key/value pairs.
    If the code involves a lot of lookup operations, Object may be a better choice in some cases .
  • Delete performance : The performance of using delete to delete Object properties has always been criticized, and it is still the case in many browsers. For this reason, there are some pseudo-delete operations of object properties, including setting property values ​​to undefined or null. But many times, this is an annoying or inappropriate compromise. For most browser engines, the delete() operation of Map is faster than insert and search. If the code involves a lot of delete operations, then Map should be chosen without a doubt.

Thirty-one, bitwise operators

There are 7 bit operators, divided into two categories:
logical bit operators: bit and (&), bit or (|), bit exclusive or (^), not bit (~)
shift operator: left shift (< <), right shift (>>), unsigned right shift (>>>), unsigned left shift (>>>)

  • Logical bitwise operators operate in the same way as logical operators, but target different objects. Logical bitwise operators operate on binary integer values, while logical operators operate on non-binary values.

Thirty-two, delete delete performance

Details
delete is a common operator that returns true or false.

  • It also returns true when the object property does not exist, so the return value is not completely equivalent to whether the deletion is successful or not.
  • Returns false if the property of the deleted object exists and has DontDelete, otherwise returns true.
  • Global scope/function code > eval . In the global scope or function code declared by var or function, it cannot be deleted by delete.

Thirty-three, the browser caches the specific cache configuration of each file

(When I answered the hash of Content-Length plus Last-modified, the interviewer was surprised by the naked eye...)

Thirty-four, Var and Let and Const

was

  • Is one of the first JavaScript keywords, a variable in JavaScript, divided into declaration and initialization.
  • var has variable promotion No matter where it is declared, variable promotion will promote it to the top of the scope, and you can access it anywhere

  • Function scope, and it can be declared multiple times, which will cause you to not know Let and Const when you overwrite it
  • has block scope
  • When a variable is promoted, there will be a temporary lock area.
  • Cannot repeat the statement, will report an error
  • The biggest difference between Const and Let is that Const is non-reassignable
  • When the value of Const is a reference type, it can be reassigned, because the reference type is actually a reference address stored in the stack space, and the real value is kept in the heap space

Thirty-five, further understanding of Const

  • Const must be initialized and assigned when it is declared, and this value cannot be modified.
  • But for reference types (such as objects, arrays, etc.), what Const actually holds is the reference address of the value in the stack at this time, and the actual data is kept in the heap, so modifying the value of the reference type at this time will not violate Const of restrictions.

Thirty-six, make the value unmodifiable even if it is a reference type

The first type: Object.freeze
is the enumerability, configurability, and writability of the existing properties of the object, and the value of the existing properties cannot be modified. This attribute is often used in the data we get from the interface. In order to avoid modification, it will be frozen after getting it.
This method can freeze the object. The frozen object has the following characteristics:

  • A frozen object can no longer be modified;
  • A frozen object cannot add new properties and cannot delete existing properties
  • A frozen object prototype cannot be modified either.

What does freeze do?

  • Set Object.preventExtension() to prohibit adding new properties (absolutely exist)
  • Set Writable to false, prohibit modification (absolutely exists)
  • Set Configurable to false to disable configuration (absolutely exists)
  • Forbids changing accessor properties (getters and setters)
    Second: Object.seal
    This method seals an object, preventing new properties from being added and marking all existing properties as non-configurable. The difference from Object.freeze is that the value of the current property of Object.seal can be changed as long as it is writable.

What did seal do?

● set Object.preventExtension(), prohibit adding new properties (absolutely exists)
● set Configurable to false, prohibit configuration (absolutely exist)
● prohibit changing accessor properties (getter and setter)

The third: Object.preventExtensions

Make an object non-extensible, that is, new properties can never be added.

Thirty-seven, arrow functions and ordinary functions

1.
Such a piece of code in function JavaScript. It is only defined once, but it can be executed or called any number of times in the required scene. The
common definition methods are as follows

● Function declaration: function functionName () {}
● Function expression: let name = function(){}
● Arrow function: () => {}
● Constructor: let name = new Function (arg1 , arg2 ,arg3 ,…, argN , body )

ps: The definition of the first and second functions is actually the grammatical sugar of the fourth constructor. When we define a function, we will create a function through new Function, but the first two are encapsulated for us. We It’s just invisible, any function in js is an instance of Function, such as the following:

  1. var arr = []; is syntactic sugar for var arr = new Array();.
  2. var obj = {} is syntactic sugar for var obj = new Object();

Difference between arrow function and normal function Difference
insert image description here
between function declaration and function expression

  • The function declaration will be promoted to the very beginning of the scope of the function, so it can be used in any direction of the scope
  • However, this does not happen with function expressions, so function expressions need to be assigned before use (function expressions are also called anonymous functions), otherwise add === undefined due to variable declaration promotion.
    ** What is the difference between a constructor and an ordinary function?
    The main difference is the difference between the function and the ordinary function
  • The same is to repeatedly execute the same piece of code
  • The difference is that the constructor is used to initialize the object, and the constructor is often used together with new, and the first letter is usually capitalized when it is defined.

Thirty-seven, symbol type

Symbol is a newly added primitive data type in ES6. Its function is to define a unique object attribute name, which is a unique label, and it is immutable.
effect:

  • As an attribute name, solve the problem of global variable name conflicts
  • Define private, define some non-private methods for objects, but want to use them only internally
  • As a unique value, in some scenarios, we don't care what the value is, then we can use symbol to represent
    the characteristics
  • Cannot be constructed using new, primitive data types Creating an explicit wrapper object is not supported since ECMAScript 6. Except for things like new Boolean, new String, and new Number, which can still be created for legacy reasons.
  • The dot operator cannot be used. When it is used as an object attribute key, when obtaining its value, it can only be obtained in the form of [], and the . operator cannot be used
  • It cannot be iterated by for in, nor can Object.getOwnPropertyNames() return the properties of the object, only Object.getOwnPropertySymbols() can be used to get them.
//可以传入参数,参数书对 symbol  的描述,可以调用,但是不能访问 symbol  本身
var sym1 = Symbol();
var sym2 = Symbol('foo');
var sym3 = Symbol('foo');


console.log(typeof sym1); // symbol

console.log(Symbol("foo") === Symbol("foo")); // false

console.log(sym2 == sym3 );//false


//Symbol 包装器对象作为属性的键
var name = Symbol("名字");
var obj = {
    
    };
obj[name] = "大黄";
// 作为对象属性 key 时,在获取其值的时候,只能使用 [] 形式获取,不能使用 . 操作符
console.log(obj);//{Symbol(name): "大黄"}
console.log(obj[name]);//大黄
console.log(obj.name);//undefined



//不能被 for in
var name = Symbol("名字");
var obj = {
    
    };
obj[name] = "大黄";
for(var key in obj){
    
    
    console.log(obj[key]);//无输出
}

// 用作唯一常量,标识符等
var animal= {
    
    
  rabbit: Symbol(),
  dog: Symbol(),
  snake: Symbol()
}

Thirty-eight, promise

  • The role of Promise.all
    details : It can be guaranteed that all promise objects in the promises array have reached the resolve state before the then callback is executed. A scenario : If each object in your promises array is an http request, or each object contains complex call processing. And there are hundreds of thousands of such objects. Then what will happen is that you send hundreds of thousands of http requests in an instant (insufficient number of tcp connections may cause waiting), or accumulate countless call stacks and cause memory overflow. Solution: Promise.all does concurrency limit. Promise.all concurrency limit means that the number of promises executed concurrently at each moment is fixed, and the final execution result remains consistent with the original Promise.all.




Solutions: tiny-async-pool, es6-promise-pool, p-limit

Thirty-nine, ... args remaining parameters (expansion operator)

Expand operator : Allows an expression to be expanded somewhere. The spread operator can be used where there are multiple parameters (for function calls) or multiple elements (for array literals) or multiple variables (for destructuring assignments).

  • 1. Use the expansion operator (parameter passing) in the function call

Before ES6, use the feature of Function.prototype.apply when passing the elements in the entire array as actual parameters to the function parameters in turn

let arr = [1,2,3]
function test(a,b,c){
    
    }
test.apply(null,args)  //通过apply特性将数值的形式转换为数组对应传递进去

Spread operator after ES6

let arr = [1,2,3]
function test(a,b,c){
    
    }
test(..arr) //将数组展开进行传递参数
  • 2. Use the spread operator in the array (merge arrays, array-like objects become arrays)
a.合并数组
let arr = [1,2,3]
let arr1 = [...arr,4,5,6]  //1,2,3,4,5,6
b.展开运算符可以用于数组的一些方法中(push函数)
let arr = [1,2,3]
let arr1 = [4,5,6]
arr1.push(...arr) //4,5,6,1,2,3
c.类数组对象变成数组
let a=new Set([1,2,3,4,5,2,1])  // a : Set(5) {1, 2, 3, 4, 5}
let b=[...a]    //  (5) [1, 2, 3, 4, 5]
  • 3. Destructuring assignment (the expansion operator in destructuring assignment can only be used at the end)
let [arg1,arg2,...arg3] = [1, 2, 3, 4] 
arg1 //1
arg2 //2
arg3 //['3','4']
  • 4. Spread operator in object (similar to array)
let {
    
    x,y,...z}={
    
    x:1,y:2,a:3,b:4};
x; //1
y; //2
z; //{a:3,b:4}
let z={
    
    a:3,b:4};
let n={
    
    x:1,y:2,...z};
n; //{x:1,y:2,a:3,b:4}
let a={
    
    x:1,y:2};
let b={
    
    z:3};
let ab={
    
    ...a,...b};
ab //{x:1,y:2,z:3}

Rest Arguments : The rest argument syntax allows us to represent an indefinite number of arguments as an array.

  • 1. Function call
function test(a,b,...args){
    
    } //...args == [4,5,6]
test(1,2,3,4,5,6)
  • 2. Destructuring assignment (the expansion operator in destructuring assignment can only be used at the end)
let [arg1,arg2,...arg3] = [1, 2, 3, 4] 
arg1 //1
arg2 //2
arg3 //['3','4']

2. The arguments object
1. Definition: arguments is an array-like object corresponding to the parameters passed to the function, and the arguments object is a local variable that all non-arrow functions have. You can refer to a function's arguments within a function using the arguments object. This object contains each argument passed to the function, with the first argument at index 0.
2. Features:

  • The arguments object is not an array, and does not have any array properties except length and index elements. Of course it can be converted to an array
const args = Array.from(arguments); 
const args = [...arguments];
  • arguments exist attribute callee:
属性callee相当于调用自身函数,可以用作匿名函数的递归:
var sum = function (n) {
    
     
if (1 == n){
    
     
return 1; 
} else {
    
    
 return n + arguments.callee(n - 1); //6 5 4 3 2 1 } } alert(sum(6)); 输出结果:21
 }

3. Function:

a.无需明确命名参数,就可以重写函数,在函数代码中,使用特殊对象 arguments,开发者无需明确指出参数名,就能访问它们
function sayHi(message) {
    
    
  alert(arguments[0]);   // 此处将打印message参数的值
}
b.检测参数个数( arguments.length )
function howManyArgs() {
    
    
  alert(arguments.length);
}
howManyArgs("string", 45);
howManyArgs();
howManyArgs(12);   //  上面这段代码将依次显示 "2"、"0" 和 "1"。
c.针对同一个方法被多处调用,但是参数数量不确定的情况下,可以更具arguments索引进行判断。
 function func1() {
    
    
            console.log(arguments[0]); // 1 
            console.log(arguments[1]); // 2 
            console.log(arguments[2]); // 3 
        }
        func1(1, 2, 3)
d.模拟函数重载
用 arguments 对象判断传递给函数的参数个数,即可模拟函数重载
当只有一个参数时,doAdd() 函数给参数加 5。如果有两个参数,则会把两个参数相加,返回它们的和。所以,doAdd(10) 输出的是 “15”,而 doAdd(40, 20) 输出的是 “60”。
function doAdd() {
    
    
  if(arguments.length == 1) {
    
    
    alert(arguments[0] + 5);
  } else if(arguments.length == 2) {
    
    
    alert(arguments[0] + arguments[1]);
  }
}
doAdd(10);	//输出 "15"
doAdd(40, 20);	//输出 "60"

Forty, ArrayBuffer

The ArrayBuffer object is an interface for JavaScript to manipulate binary data. A separate specification (published February 2011), ES6 incorporated them into the ECMAScript specification. It handles binary data in the syntax of an array, so it is called a binary array.
It is against this background that binary arrays were born. It allows developers to directly manipulate memory in the form of array subscripts, which greatly enhances the ability of JavaScript to process binary data.
The binary array consists of three types of objects
: ArrayBuffer, TypedArray, and DataView.
Simply put, the ArrayBuffer object represents the original binary data, the TypedArray view is used to read and write simple types of binary data, and the DataView view is used to read and write complex types of binary data.

It is already very powerful to be able to master the common JS knowledge points above! The editor has sorted out these at present, and will update them in the future~ Everyone can learn and summarize together!
insert image description here

Guess you like

Origin blog.csdn.net/qq_59079803/article/details/124106843