A set can be initialized by taking an array or an array-like object as an argument
Eg: let set = new set ([1,2,3,4,5])
WeakSet: Cannot receive object initialization.
2. Different members
Set can include string number Array NULL Boolean function Object
WeakSet members can only be Objects
3. Different attributes
Set has a size attribute. WeakSet has no size attribute
4. Different methods
1) Set operation method
.add(value)
.delete(value)
.has(value)
.clear() clears all
2) Have traversal method
.keys() returns the key name
.vlaues() returns a traverser for key values
.foreach () iterates through each member.
3) weakSet operation method:
.add(value)
.delete(value)
.has(value)
No size property, so no traversal.
Difference between Map and WeakMap WeakMap only accepts objects as key names (except null), and does not accept other types of values as key names. WeakMap’s key name points to objects that are not included in the garbage collection mechanism. WeakMap has no traversal operation and no size attribute.
2, type conversion:
Cast: parseInt() parsetFloat() number()
Implicit type conversion: + * ==
Create array:
let arr = [] let arr2 = new Array() letArr3 = Array of (1, 2, 3, 4)Copy the code
Arr instanceof Array
This method looks up the prototype chain to see if the prototype of the object on the left has the same prototype property as the constructor on the rightfunction instance_of(l,R){
let o = R.prototype
let L = l.__proto__
while(true) {if(L === null){
return false
} else if(o === L){
return true;
}
L = l.__proto__;
}
}
Array.isArray(arr)
Object.prototype.toString().call()
Copy the code
5, array operation method
Pop (): tail deletion, which returns the deleted element
Push (): tail adds unshift(): header adds
Shift (): Header delete returns the deleted element
6. Create ten A labels and pop up the corresponding serial number when clicking
let i;
for( i = 0,i<10,i++){
a = document.createElement('a')
a.innerHtml = i + '<br>'
a.addEventListener('click'.function(e){
alert(i)
})
document.body.appendChild(a)
}Copy the code
7. Split (),join() Split () splits a string into an array, and join() converts an array to a string
8, IE and standard compatibility writing method
var ev = ev || window.event
var clientwidth = document.documentElement.clientWidth || document.body.clientWidth
var target = ev.srcElement || ev.targetCopy the code
Get request parameters are placed after the URL, and the size is limited. Post requests are placed in virtual carriers
Object.call(this,obj1,obj2) object. apply(this,[obj1,obj2])
Event delegate what is the use of event bubbling and event source objects, let itself trigger the event, let the parent element instead of executing! Prevent event bubbling, and default behavior
W3c: e.topPropagation () prevents bubbles. E.preventdefault Prevents default behavior. IE: e.ancelBubble =truePrevent bubbling e.returnValue =falseBlocking default behaviorCopy the code
A function closure that can access a variable in another function’s scope is a function that can access a variable in another function’s scope.
Create createElement(‘a’);
Create an A tag createElement('a'CreateTextNode () Delete removeChild() replace replaceChild() insert insertBefore()Copy the code
15. Principle of JSONP
The SRC attribute of script tag is not affected by the same origin policy. By passing the front-end method as a parameter to the server, and then the server will inject parameters and then return, the server can communicate with the client to create script tag dynamically
The implementation codefunction jsonp(req){
var script = document.createElement('script')
var url = req.url + '? callback='+ req.callback
script.src = url
document.getElementsByTagName('head')[0].appendChild(script)
}
function hello(res){
console.log('hello'+res.data)
}
jsonp({
url:' ',
callback:hello
}) Copy the code
16. Documnet Load vs. Document Ready
Document.onload is executed after the structure and style, external JS, and image have been loaded
17. The difference between == and ===
== automatically converts the type and determines whether it is equal. === No type conversion occurs.
Function declarations and function expressions
Function declaration: the JS parser reads the function declaration first, and the function expression is available before it executes the code: it will not be parsed until the JS parser reaches its line of code.
Javascript event flow ‘DOM event flow ‘: three stages: event capture, target stage, event bubbling
Null and undefined
Null indicates that there is no object, and the value is 0; Undefined indicates the original value of none, which is NaN when converted to a value. When the declared variable has not yet been initialized
21, Create new
function my_new(fn){
let obj = {
__proto__:fn.prototype
}
fn.call(obj,arguments)
return obj
} Copy the code
22. The core of the JS language inheritance mechanism is (prototype). When the JS parsing engine reads the value of the property of an Object, it will look up along the (prototype chain). If the value of the property is found, the result is returned.
Cookie, LocalStorage and SessionStorage difference
Data lifecycle:
Cookies are generally generated by the server and the expiration time can be set. If cookies are generated on the browser, they will be invalid after the browser is closed by default. LocalStorage: always save SessionStorage unless cleared: only valid for current session, cleared after closing the browser.
Storage data size:
Cookies are about 4KB localStorage and sessionStorage are usually 5MB
Communicate with the server:
Cookies are carried in HTTP headers each time and can cause performance problems if too much data is stored. SessionStorage and localStorage are stored only in the client and do not communicate with the server. SessionStorage and localStorage can only store strings and can store objects after json.stringify ().
Get the maximum value in the array
letArr = [2,3,4,5,6,7] math.max. Apply (Math,arr) math.min. Apply (Math,arr)Copy the code
25. Slice and Splice
Slice (start,end) truncated from start to end Does not include the set of truncated elements whose end return value is unchanged
Splice (start, deleteCount, item1, item2) start to start the location of the number of deleteCount to capture / / for 0 means not to delete elements, from the starting position to add a few elements into the original array. Items is the element to add.
26. What happens from entering the URL to loading the page
1. DNS resolution
2. TCP connection
3. Send the HTTP request
4. The server processes the request and returns the packet
5. The browser parses the rendered page
6. The connection ends
27, shake and throttle
Anti-shake: The function is executed only once within n seconds after the high-frequency event is triggered. If the high-frequency event is triggered again within n seconds, the time is recalculated.
function debounce(fn){
let timeout = null
return function(){
clearTimeout(timeout);
timeout = setTimeout(()=>{
fn.apply(this,arguments)
},500)
}
}Copy the code
Throttling: A high-frequency event fires, but only executes once in n seconds, so throttling dilutes the execution frequency of the function.
function throttle(fn){
let canRun = false
return function() {if(canRun) return;
canRun = true
setTimeout(()=>{
fn.apply(this,arguments)
canRun = false}}}, 500)Copy the code
Implement deep copy of object
function deepCopy(target,source) {for(let index in source) {if(typeof source[index]==="object"){
target[index] ={} deepCopy(target[index],source[index])
}else{ target[index] = source[index] }
}
}Copy the code