Take your front end pinch to death, every day to learn cool cool, dada front programmer, wechat search [programmer Doraemon] pay attention to this different programmer.
Thank you for every programmer who loves the front end, no matter how strange the front end skills are, welcome to pay attention to add me to the group
preface
I hope I can get help for you through this article.
1. Understanding of JavaScript garbage collection mechanism
There is no fixed size for strings, objects, or arrays in JavaScript. Only when they are allocated dynamically, the interpreter allocates memory to store the data. When the JavaScript interpreter consumes all available memory in the system, the system crashes.
Memory leakage. In some cases, the memory occupied by unused variables is not released in time. As a result, the memory occupied by the program runs becomes larger and larger.
So, JavaScript has its own garbage collection mechanism, the JavaScript interpreter can detect when the program is no longer using the object (data), it will free up the memory.
There are two (commonly used) approaches to JavaScript’s come and go recycle mechanism: tag cleanup and reference counting.
Mark clear
The garbage collector marks variables as “in” when they enter the execution environment and “out” when they leave the environment.
Garbage collector at run time adding tags to all variables stored in the memory, then remove the environment in the environment variables, and the environment variables referenced in the tag, after that be add tag variables will be deemed to be ready to remove, is to delete variables, the garbage collector to complete memory cleanup, destruction of these with the value of the tag, Reclaim the memory space they occupy.
Reference counting
Reference counting is a garbage collection strategy that keeps track of how many times each value is referenced.
When a variable is declared and a reference type is assigned to the variable, the number of references to the value is 1.
Conversely, if the value of the variable changes to another, the number of references to that value is reduced by one. (When the number of references to this value is zero, no variable is in use and the value cannot be accessed.) Therefore, the space it occupies can be reclaimed, so that the garbage collector will clean up the space occupied by the zero reference value at run time.
But reference counting exists and if there are a lot of references to each other it will cause a lot of memory leaks; It can also cause memory leaks if there is a circular reference problem.
So, reduce garbage collection in JavaScript, create new objects at initialization, and then reuse them as much as possible. We can: 1. Array optimization; 2. Optimize the object as much as possible; 3. Cycle optimization.
The following memory allocation modes are used:
Create a new object [] Create a new array funtion(){... } create a new method new Foo() new keyword, a memory allocationCopy the code
Reuse: Optimization of an object by iterating through all properties of the object, deleting properties one by one, and finally empting the object into an empty object.
2. There are several types of DOM nodes
Well, ok, the DOM node types are: Document node, the entire Document is a Document node; Element nodes, where each HTML tag is an Element node; Attribute nodes, where each HTML Attribute is an Attribute node; Text nodes. The Text contained within an HTML element is a Text node.
3. The difference between defer and async properties in the Script tag
Typically, script download and execution will be synchronized according to the sequence of documents. When the script is downloaded and executed, document parsing will be blocked and the document parsing will continue until the script is downloaded and executed.
If there is no defer or async attribute in the Script tag, when the browser encounters the Script tag during rendering, it stops rendering to download and execute the JS code, and then resumes rendering from where it left off when the JS execution is complete.
As you will know, this can cause browser congestion. If you want your project’s first screen to render quickly, try not to load JS files on the first screen, so it is recommended to put the script tag at the bottom of the body tag while studying.
Speaking of the difference between defer and async properties, here are three cases where script tags can be used:
<script SRC ="dadaqianduan.js"></script> // The browser will immediately load and execute the corresponding script <script async SRC ="dadaqianduan.js"></script> // <script defer SRC ="dadaqianduan.js"></script> // The process of loading the following documents and loading the JS script is carried out in parallel. The execution of the js script must wait until all elements of the document have been parsed and before the DOMContentLoaded event triggers executionCopy the code
When multiple JS scripts are loaded, async loads in random order, while defer loads in sequential order. The defer attribute indicates that the introduced JavaScript is delayed. The HTML parsing does not stop when this JavaScript is loaded, so defer does not block HTML parsing. It waits for the Dom to load before executing the JavaScript code. (When the DEFER attribute is encountered during THE HTML parsing process, the JS file will be loaded asynchronously without interrupting the parsing of the HTML document. When the entire HTML parsing is complete, the JS file will be parsed again.)
- When the defer property is present, the loading of the script and the document happens asynchronously, and the script is not executed until the document has been parsed.
- When async property is present, the script loading process and document loading also occur asynchronously. Note here that after the script is downloaded, the HTML parsing will be stopped, the script will be executed first, and the HTML parsing will continue after the script is parsed.
- With both async and defer properties, the execution is the same as async.
The defer property – whether to defer executing the script until the page loads; Async property – Scripts are executed asynchronously once they are available. The defer attribute loads the JavaScript files in parallel and executes them in the order of the Script tags on the page, while async loads in parallel and executes them as soon as the download is complete rather than in the order on the page.
4. Tell me what you know about closures
At the beginning of an interview, what should you say when asked about your understanding of closures?
In simple terms, a function defined inside a function holds references to variables or arguments inside an external function. Internal functions depend on external functions, and external function parameters and variables are not collected by the garbage collection mechanism. These variables are always in memory.
The advantage is that it can read variables inside the function and avoid pollution of global variables. The disadvantage is that it will increase the memory usage and easily lead to memory leakage. The solution is to delete all local variables that are not applicable before exiting the function. In JavaScript, functions are closures, and only functions have scopes.
Closure features, functions nested functions, inside the function can reference external parameters and variables, parameters and variables are not garbage collection mechanism.
Because in js, belong to the scope of the variable function scope, after the function, the scope will be clear, the memory will be recycled, but because of the closure is based on a function within the function, because the child function can access the superior scope of reason, even if the superior function performed, scope will not be destroyed.
In essence, a closure is a bridge between the inside and outside of a function.
Code closure representation:
// Pass var a = 1 as a function argument; function foo() { var a = 2; function dada() { console.log(a); } da(dada); } function da(fn) {// closure fn(); } foo(); 2 / / outputCopy the code
5. Explain the unshift() method
The unshift() method can add one or more elements to the beginning of an array and return the new length.
arrayObject.unshift(newelement1,newelement2,.... ,newelementX) newelement1 required. The first element added to the array. Newelement2 optional. The second element added to the array. NewelementX optional. Several elements can be added.Copy the code
Return value – New length of arrayObject.
The unshift() method inserts its arguments into the head of the arrayObject and moves the existing elements sequentially to the higher subscript to leave space. The first argument to the method will be the new element 0 of the array, if there is a second argument, it will be the new element 1, and so on.
Note that the unshift() method does not create a new creation, but modifies the existing array directly. This method changes the length of the array.
6. What encodeURI() and decodeURI() do
1. EncodeURl () is used to convert urls to hexadecimal codes. 2. DecodeURI () is used to convert the encoded URL back to the normal URL.
7. Why not use innerHTML in JavaScript
The innerHTML content is refreshed every time, so it is slow. There is no room for validation in innerHTML, so it is easier to insert error code into the document, making the page unstable.
8. How to create, add, remove, replace, insert, and find nodes in DOM operations
DOM node operation method:
- Access and obtain nodes
document.getElementById(id); / / returns the id of the first object to have accessed the document. The getElementsByName (name); / / return with a specified name node collection document. The getElementsByTagName (tagName); / / return with objects in the specified tag name for the document. The getElementsByClassName (className); // Returns a collection of objects with the specified class nameCopy the code
- Create nodes/properties
CreateDocumentFragment () // Create a DOM fragment document.createElement(eName); // Create a node document.createAttribute(attrName); // Create an attribute document.createTextNode(text) for a node; // Create a text nodeCopy the code
- Add a node
document.insertBefore(newNode, referenceNode); Parentnode.appendchild (newNode); // Insert parentNode.appendChild(newNode); // Add child nodes to a nodeCopy the code
- Copy the node
cloneNode(true | false); // Copy a nodeCopy the code
- Remove nodes
parentNode.removeChild(node); // Delete the child node of a node node is the node to be deletedCopy the code
- Attribute operation
GetAttribute (name) // Obtain the value of a node attribute by the attribute name setAttribute(name,value); RemoveAttribute (name); // Delete an attributeCopy the code
- Gets adjacent nodes
curtNode.previousSibling; // Get the last node (curtNode.nextsibling) of the known node; // Get the next node of a known nodeCopy the code
9. How to achieve communication between multiple tabs in the browser
Use localStorage. SetItem (key,value). Add content
Use storage events to listen for add, modify, or delete actions
window.addEventListener("storage",function(event){
$("#name").val(event.key+"="+event.newValue);
});
Copy the code
$(function(){
$("#btn").click(function(){
var name = $("#name").val();
localStorage.setItem("name", name);
});
});
Copy the code
What is the difference between null and undefined
console.log(null==undefined)//true
console.log(null===undefined)//false
Copy the code
Null: Type null, representing “null value”, representing a null object pointer
Undefined: undefined is used when a variable is declared uninitialized
Undefined means “missing value”. There should be a value here, but it is not defined yet.
Null means “no object” and there should be no value.
11. What does the new operator do
The new operator first creates an empty object:
var obj = new Object();
Copy the code
Set the prototype chain:
obj._proto_ = Object.prototype
Copy the code
The sample code learns what new does:
function da(name) {
this.name = name;
}
da.prototype.sayName = function() {
console.log(this.name);
}
const jeskson = new da('dada');
console.log(jeskson.name); // dada
jeskson.sayName(); // dada
Copy the code
From the examples:
The instance created by new through the constructor da has access to properties in the constructor
An instance created by new through the constructor da has access to properties in the constructor prototype chain.
If you give the constructor a return value, (there is no explicit return value, undefined is returned by default)
function da(name) {
this.name = name;
return 1;
}
const jeskson = new da('dada');
console.log(jeskson.name); // dada
Copy the code
The return value is of no use. If the constructor returns the original value, the return value is meaningless.
function da(name) {
this.name = name;
console.log(this); // da {name: 'dada'}
return {age:1}
}
const jeskson = new da('dada');
console.log(jeskson); // {age:1}
console.log(jeskson.name); // undefined
Copy the code
If the constructor returns an object, the return value is used normally.
- The new operator returns an object
- This object, the this in the constructor, can access any property mounted on this
- This object has access to properties on the constructor prototype
- The return of the original value is ignored, and the returned object is processed normally
12. What are the ways of JavaScript lazy loading
Lazy loading of JS helps speed up page loading
There are defer attributes, async attributes, dynamically creating the DOM, using JQuery’s getScript method, and setTimeout delay methods to let the JS load last.
Use the setTimeout delay method
<script type="text/javascript" > function A(){ $.post("/lord/login",{name:username,pwd:password},function(){ alert("Hello"); }); } $(function (){ setTimeout('A()', 1000); // Delay 1 second}) </script>Copy the code
13. What are the differences between call() and apply()
Call () and applay() belong to a Function. Prototype method that is implemented in the JavaScript engine and belongs to Function. Prototype.
Call () and apply() do the same thing, except that they take different parameters.
call(this, arg1, arg2, arg3); apply(this, arguments); function add(a,b){ console.log(a+b); } function sub(a,b){ console.log(a-b); } add.call(sub, 2, 1); The add. Apply (sub, (2, 1]);Copy the code
For A.applay(B) or A.call(B), simply put, B executes first, then executes A based on the result, uses A to execute B’s content code, and then executes its own code.
var f1 = function(a,b) {
console.log(a+b);
}
var f2 = function(a,b,c) {
console.log(a,b,c);
}
f2.apply(f1,[1,2]) // 1 2 undefined
Copy the code
F1 (); f1(); f1(); f1(); F2 executes this to the window. Parameter [1,2], parsed parameter 1,2,undefined; After the f2 method is executed, the output values are 1, 2, undefined
A.call(B, 1,2,3); a. call(B, 1, 3);
var f1 = function(a,b) { console.log(a+b); } var f2 = function(a,b,c) { console.log(a,b,c); } f2. Call (f1, [1, 2]); // [1,2] undefined constant f2.call(f1, 1,2); // 1 2 undefinedCopy the code
[1,2]; [1,2]; [1,2]; [1,2];
Use apply() and call() :
/ / apply use var arr = new Array (1, 2, 3) var arr1 = new Array (11,21,31) Array. The prototype. Push. Apply (arr, arr1) console.log(arr)//[1, 2, 3, 11, 21, Var arr = new Array(1,2,3) var arr1 = new Array(11,21,31) Array.prototype.push.call(arr,arr1[0],arr1[1],arr1[2]) console.log(arr)//[1, 2, 3, 11, 21, 31]Copy the code
Arrays are maximized and minimized by Math
Var _maxNum = math.max. apply(null,[1,3,2,4,5]) console.log(_maxNum)//5 var _minNum = Math.min.apply(null,[1,3,2,4,5]) console.log(_minNum) var _maxNum = math.max. call(null,1,3,2,4,5) var _maxNum = math.max-call (null,1,3,2,4,5) Log (_maxNum)//5 var _minNum = math.min. call(null,1,3,2,4,5) console.log(_minNum)//1Copy the code
Function.prototype.call (); function.prototype. call (); The first argument specifies the point of this in the function; The second argument is different. Apply passes in a collection, array, or class array with a lower index. Apply passes it to a function as an argument. Call performs better than Applay and is often used.
Especially since ES6 introduced the Spread operator extension operator, call can be used even if the arguments are arrays.
Let the params = [1, 2, 3, 4, 5]; dada.call(obj, ... params);Copy the code
The first argument passed in is null, and this in the function body points to the default host object, or window in the browser
var func = function( a, b, c ){ console.log(this === window); // Output :true}; func.apply( null, [ 1, 2, 3 ] ); Var func = function(a, b, c){"use strict"; console.log(this === null); // Output :true}; func.apply( null, [ 1, 2, 3 ] );Copy the code
Change the direction of this
var obj1={ name: 'dada' }; var obj2={ name: 'da' }; window.name = 'window'; var getName = function(){ console.log ( this.name ); }; getName(); // Output: window getName.call(obj1); // Output: dada getName.call(obj2); // Output: daCopy the code
document.getElementById( 'div1' ).onclick = function(){ console.log( this.id ); Div1 var func = function(){console.log (this.id); // undefined} func(); }; Document.getelementbyid ('div1').onclick = function(){var func = function(){console.log (this.id); // Output: div1} func.call(this); };Copy the code
14. Which operations are causing memory leaks
15. Talk about several ways to create JavaScript objects
Factory mode, creation mode
function createPerson(name,age,job){
var o = new Object();
o.name=name;
o.age=age;
o.job=job;
o.sayName = function(){
alert(this.name);
}
}
var person1 = createPerson("da",1,"it");
var person2 = createPerson("dada",2,"it");
Copy the code
Constructor pattern
function Person(name,age,ob){
this.name=name;
this.age=age;
this.job=job;
this.sayName = function(){
alert(this.name);
}
var person1 = new Person("dada",1,"web");
var person2 = new Person("dada",2,"web");
}
Copy the code
Using prototype patterns:
function Person(){
}
Person.prototype.name = "da";
Person.prototype.age = 1;
Person.prototype.job = "web";
Person.prototype.sayName = function(){
alert(this.name);
}
var person1 = new Person();
person1.sayName(); //"dada"
var person2 = new Person();
person2.sayName(); //"dada"
alert(person1.sayName == person2.sayName); //true
Copy the code
Use a combination of constructor and stereotype patterns
function Person(name,age){
this.name = name;
this.age = age;
this.friends = ["da","dada"];
}
Person.prototype = {
constructor:Person,
sayName:function(){
alert(this.name);
}
}
var person1 = new Person("da1",1);
var person2 = new Person("da2",2);
person1.friends.push("dadada");
console.log(person1.friends); //["da","dada","dadada"]
console.log(person2.friends); //["da","dada"]
console.log(person1.friends === person2.friends); //false
console.log(person1.sayName === person2.sayName); //true
Copy the code
Dynamic prototype pattern
function Person(name,age,job){
this.name=name;
this.age=age;
this.job=job;
if(typeof this.sayName!="function"){
Person.prototype.sayName=function(){
alert(this.name);
};
}
}
Copy the code
JavaScript Object creation way, 1, the Object constructor type, 2, and Object literal type, 3, the factory pattern, 4, safety factory pattern, 5, the constructor mode, 6, prototype model, 7, blend the constructor and the prototype model, 8, dynamic prototype model, 9, parasitic constructor mode, 10, err on the side of the constructor mode.
16. How to implement asynchronous programming
Learning to use asynchrony is important. On the browser side, long operations should be performed asynchronously to avoid the browser becoming unresponsive. The best example is Ajax operations.
Var promise = function() {this.callbacks = []; var promise = function() {this.callbacks = []; Prototype = {construct: Promise, resolve: function(result) {construct: Promise, resolve: function(result) {reject: Complete: function(type, result) {// execute callback}, then: function(type, result) {// execute callback} Function (successHandler, failedHandler) {// Bind callback function}}Copy the code
For callback functions, the advantages are simple and easy to understand, but the disadvantages are that the code reading and maintenance, the various parts of the highly coupled, the process can be messy, each task can only specify one callback function, called: callback hell.
// synchronous operation becomes asynchronous operation f1(); f2(); function f1(callback) { setTimeout(function() { callback(); }, 1000); } f1(f2);Copy the code
An example of event listening (in event-driven mode, where the execution of tasks depends not on the order of the code but on whether an event occurs) is as follows:
$('#clickBtn').on('click',function(e){console.log('xxx'); }Copy the code
f1.on('dada', f2); function f1() { setTimeout(function() { f1.trigger('dada'); }, 1000); } // f1.trigger('dada') indicates that a Dada event is triggered immediately after the execution is complete and f2 is executedCopy the code
For event monitoring, can bind multiple events, and each event can specify multiple callback functions, can be “decouple”, is conducive to modular implementation, the disadvantage is that the whole program to program event-driven, the running process will become very unclear.
For publish, subscribe, and “event listening”. (Publish/subscribe)
With the Promise object implementation, each asynchronous task returns a Promise object that has a THEN method that allows the callback function to be specified.
17. Talk about JavaScript’s same-origin policy
The purpose of the same origin policy is to prevent a document or script from being loaded from multiple sources. The same origin policy means that the protocol, domain name, and port are the same. The same origin policy is a security protocol that allows a script to read only the properties of Windows and documents from the same source.
18. Explain why there is a homology restriction
There are origin restrictions that can place hackers to steal information.
19. In JavaScript, why do we say functions are first class objects
Functions are objects of the first class:
These functions can be passed as arguments to other functions, returned as values of other functions, assigned to variables, or stored in data structures.
If citizens are divided into classes, first-class citizens can do everything, and second-class citizens cannot do this or that. JavaScript functions are objects, they can have properties, they can be assigned to a variable, they can be placed in an array as an element, they can be properties of other objects, they can do anything, they can do anything other objects can do, they can do anything other objects can’t do. That’s what first-class citizenship is all about.
20. The difference between function declarations and function expressions
Function declaration:
foo(); // Call foo after the function declaration, which works fine. Because foo was defined first. function foo() { return true; }Copy the code
Call:
Function name (parameter) Function name. call(function name, parameter) function name. apply(function name,[parameter]) new Function name (parameter) Timer converts function declarations into function expressions and calls template strings in ES6Copy the code
Function expression:
foo(); // Call function before function expression, error. Because we don't have the variable foo yet. var foo = function() { return foo; };Copy the code
call
Function name (parameter) function name.call (parameter) function name.apply (function name,[parameter]) new Function name.apply (function name,[parameter]) new Function name (parameter)Copy the code
When loading data into the execution environment, the parser treats a function declaration differently than a function expression. The parser reads the function declaration first and makes it available before executing any code. In the case of a function expression, it waits until the parser reaches its line of code.
There is a mechanism in the JavaScript interpreter for variable declarations to be promoted, which means that function declarations are promoted to the front of the scope, even when the code is written at the back.
Var getName // is promoted, Var getName = function() {console.log('da') da function getName() { console.log('dada') } getName() // daCopy the code
There are four ways to define a function in JavaScript
3. ES6 arrow Function 4. New Function()Copy the code
- ES5 states that functions can only be declared in top-level and function scopes, otherwise it is illegal.
- ES6 introduces the concept of block-level scope, and this definition is allowed.
21. How do I delete a cookie
The code is as follows:
document.cookie = 'user=jeskson; expires='+new Date(0);Copy the code
22. Write a method to find the length of a string
An English character occupies one byte, and a Chinese character occupies two bytes
function byte(str) {
var bytes = str.length;
for(var i=0; i<bytes; i++) {
if(str.charCodeAt(i)>255) {
bytes++;
}
}
return bytes
}
console.log(byte('dada'));
Copy the code
23. What is the difference between attribute and property
An attribute is a property that a DOM element has in a document as an HTML tag, and a property is a property that a DOM element has as an object in JavaScript.
Attribute Indicates the property attribute.
24. What is the role of deferred scripting in JavaScript
By default, parsing of the HTML code is paused during page loading until the script stops executing. If the server is slow or the script is particularly heavy, the web page will be delayed, and with Deferred the script will be delayed until the HTML parser runs. This reduces the load time of web pages, and they display faster.
25. What is a closure and what are its advantages and disadvantages
Outer () {var a = function() {console.info(a); } return inner; // Inner is a closure function because it can access outer's scope}Copy the code
Closures are a feature of JavaScript, and many advanced applications rely on closures. Because the closure will make the variables in the function are saved in memory, memory consumption is very high, so do not abuse the closure, otherwise it will lead to page performance problems, in IE may lead to memory leaks, so you can before returning to the function, remove all the local variables that are not used.
26. Determine whether an object belongs to a class
- The instanceof keyword determines whether an object is an instantiated object of a class
- The constructor property, which determines whether an object is a class constructor
27. You know a function that performs a direct object lookup but never looks up a prototype
hasOwnProperty
28. Difference between document.write and innerHTML
- Document.write redraws the entire page
- InnerHTML redraws a part of the page
Effect dynamic diagram:
<button onclick="fun()" > </button> <script> function fun() {document.write("write content "); </script> <button onclick="fun()"> </script> function fun() { Document.getelementbyid ("p").innerhtml =" new innerHTML content "; } </script>Copy the code
29. What is the way to read a file in JavaScript
Read the contents of a file in the server
Function readAjaxFile(url) {// create XHR var XHR = new XMLHttpRequest(); Xhr.onreadystatechange = function() {if(xhr.readyState === 1 &&xhr.status === = 200) {// Xhr.onReadyStatechange = function() { Console. log(xhr.responsetest)}} // Open request xhr.open('GET', url, true) // send data xhr.send(null)}Copy the code
Read the contents of the local computer
function readInputFile(id) { var file = document.getElementById(id).files[0]; Var reader = new FileReader(); Onload = function(data) {console.log(data, this.result); }}Copy the code
30. How do I assign object attributes
document.form.action = 'submit';
Copy the code
31. Basic specifications for commonly used JavaScript statements
- Do not declare multiple variables on the same line
- Use object literals instead of the new Array form
- Do not use global functions
- The switch statement must have a default branch
- A function should not sometimes return a value and sometimes not return a value
- The for loop must be enclosed in braces
- If statements must be enclosed in braces
- Write a comment
- Naming rules, constructor functions begin with a capital letter
32. What does Eval do
The eval function is to parse the corresponding string into JavaScript code and run it. However, eval should be avoided. Using eval can make your program insecure and affect performance by parsing into JavaScript statements once and executing them once.
33. The results are as follows:
["1","2","3"].map(parseInt)
Copy the code
[1,NaN,NaN] Because parseInt needs two parameters val,radix, where radix represents the radix used in the analysis, map passed 3 parameters item, index, array, the corresponding radix is illegal, so the analysis failed.
34. Say something about this object
This refers to the object on which the function is called. In general, this is the Global object and can be called as a method. The value of this changes depending on where the function is used.
This refers to whoever calls it, and in the global context, to the Window object.
var name = 'jeskson';
function person() {
return this.name;
}
console.log(this.name); // jeskson
console.log(window.name); // jeskson
console.log(person()); // jeskson
Copy the code
Local environment:
var name = "jeskson";
function person() {
console.log(this.name);
}
person(); // jeskson
var obj = {
name: "dada",
person: function() {
console.log(this.name);
}
}
obj.person(); // dada
Copy the code
Use this inside the constructor
function Person(name) {
this.name = name;
return name;
}
console.log(new Person('jeskson').name); // jeskson
Copy the code
Use the apply and call functions to redirect this
function person() {
return this.name;
}
var obj = {
name: 'jeskson'
}
console.log(person.call(obj)); // jeskson
console.log(person.apply(obj)); // jeskson
Copy the code
Object function calls, which object calls refer to the same object
<input type="button" id="btnDa" value="dada"> <script> var btnDa = document.getElementById("btnDa"); btnDa.onClick=function() { console.log(this); // this refers to the btnDa object} </script>Copy the code
Instantiate the object with new, and this in the constructor points to the instantiated object
var show = function() { this.myName="jeskson"; } var obj = new show();Copy the code
35. What is a class (pseudo) array in JavaScript and how do I convert a class (pseudo) array to a standard array
- A typical class (pseudo) array is the argument of a function in the call
getElementsByTagName
anddocument.childNodes
Method, they returnNodeList
Objects are pseudo-arrays. - You can use
Array.prototype.slice.call(fakeArray)
Convert an Array into a real Array object.
What is a pseudo-array is an object with a length property that can be converted to a real Array using array.prototype. slice.
Var da = {0: 'a', 1: 'b', length: 2}; var dada = Array.prototype.slice.call(da); console.log(da[0]); // a var dadada = [].slice.call(dada); console.log(da[0]); // aCopy the code
Pseudo-arrays: You can’t use the array methods and apis, but you can still iterate over them using convenient arrays.
A pseudo Array Array. Prototype. Slice. The call () into a true Array
36. What are the functions of callee and Caller in JavaScript
- Caller returns a reference to a function that calls the current function
- Callee returns the body of the function being executed, that is, the specified function object
Caller is an attribute of a JavaScript function type that refers to a function that calls the current function; Callee is not a property of a function object; it is a property of the Arguments object in the function context.
37. Count the number of letters in a string or the most counted letters:
aaaabbbccccddhgddada
Copy the code
function dealStr(str) {
var obj = {};
for(var i = 0; i<str.length; i++){
var v = str.charAt(i);
if(obj[v] && obj[v].value === v) {
++obj[v].count
}else{
obj[v] = {
count: 1,
value: v
}
}
}
return obj;
}
var obj = dealStr(str);
for(key in obj) {
console.log(obj[key].value+'='+obj[key].count);
}
Copy the code
38. Write a function that clears Spaces before and after strings
function trim(str) { if (str && typeof str === "string") { return str.replace(/(^\s*)|(\s*)$/g,""); // Remove before and after whitespace}}Copy the code
39. Write a function to implement an array merge method
For loop array
var arr3 = []; Arr1 for (var I = 0; i < arr1.length; i++) { arr3.push(arr1[i]); } // arr2 for (var j = 0; j < arr2.length; j++) { arr3.push(arr2[j]); } console.log(arr3); / / [6]Copy the code
Concat () method :concat() method that joins two or more arrays and returns a new array.
var arr3 = arr1.concat(arr2); console.log(arr3); / / [6]Copy the code
The apply () method
arr1.push.apply(arr1, arr2);
Copy the code
40. What are the common logical operators in your work
&&
The operator||
The operator!
The operator
41. What is event Broker (Event Delegate)
Event proxy, also known as event delegate, is to delegate the event that originally needs to be bound to the parent element, and let the parent element be responsible for event monitoring. The principle of event proxy is the event bubble of DOM elements, and the advantage of using event proxy is to improve performance.
42. What are undeclared and undefined variables
- Undeclared variable A variable that does not exist and is not declared. If a program tries to read the value of an undeclared variable, it encounters a runtime error.
xxx is not defined
Copy the code
- An undefined variable is a variable declared in a program that has not yet been given any value. If a program tries to read the value of an undefined variable, the undefined value is returned.
Declared by the var directive, but no assignment, no type defined, so undefined is printed
43. What are global variables, how are they declared, and what are the problems with using them
Family variables are variables that are available throughout the code and have no scope. The var keyword is used to declare local variables or objects. If omitted, a global variable is declared.
The problem with using global variables is that the names of local and global variables conflict, making it difficult to debug and test code that depends on global variables.
44. The disadvantages of using timers
setTimeout(function,delay)
The function is used to start a timer that calls a particular function after the owning delay.setInterval(function,delay)
The function is used to perform a given function repeatedly during the mentioned delay, stopping only on cancellation.clearInterval(id)
The function tells the timer to stop.
45. What is the difference between ViewState and SessionState
- ViewState is used for pages in the session
- SessionState is used for user-specific data accessed on all pages in a Web application
46. What is= = =
The operator
=== is the strict equality operator that returns true only if both operands have the same value and type
What are the loop structures in JavaScript
for, while, do... While, for_in, for of (es6 new) while(conditional expression statement) {execute statement block; } do {execute statement block; } while(conditional expression statement); For (initializes the expression; Cyclic condition expression; Operation expression after loop) {execute statement block; }Copy the code
48. What does null mean in JavaScript
- Null is used to indicate no value or object, no object or empty string, no valid Boolean value, and no numeric and array objects.
49. What does the delete operator do
- The delete operator is used to delete an attribute in an object, but not variables, functions, and so on.
var obj = { name: 'jeskson' } console.log(obj.name); //'jeskson' delete obj.name; console.log(obj.name); //undefinedCopy the code
50. What types of pop-up boxes are available in JavaScript
alert, confirm, prompt
51. What does the common void(0) do
It is used to prevent page refresh and passes the parameter “0” when called; Used to call another method without refreshing the page
52. What are JavaScript cookies
Cookies are data stored in text files on your computer. When a Web server sends a Web page to a browser, the server does not record the user’s information after the connection is closed.
Cookie is a pair of name=value. The Cookie string must end with a semicolon. In addition to the name attribute, cookies also have four other related attributes.
The syntax for setting a Cookie is as follows: set-cookie :name=value; [expires=date]; [path=dir]; [domain=domainn]; [secure]Copy the code
53. Explain the pop() method in JavaScript
The pop() method takes the last element out of the given array and returns it
var da = [ 1, 2, 3]; da.pop(); / / da: [1, 2]Copy the code
54. In JavaScript, what are the two base groups of datatypes
The two base groups of datatypes are primitive types and reference types.
55. What is typeof used for
Typeof is an operator that returns a string description of a variable type.
56. What does the push method do in JavaScript
The push method adds or appends one or more elements to the end of an array.
57. What does the unshift method do in JavaScript
The unshift method adds one or more elements to the beginning of an array.
58. How do I add attributes to an object
There are two common methods for adding attributes to objects:
- Bracketed syntax
- Some grammar
59. Talk about window.onload and onDocumentReady
Both of these functions can be used to perform tasks when a page is loaded into the browser, but there are subtle differences in how and when they are performed.
When the browser loads the DOM tree and all other resources (such as images, objects, etc.), “window.onload” executes the code.
OnDocumentReady is executed when the DOM tree is built without waiting for other resources to load. This allows for faster code execution against the DOM using onDocumentReady.
Another difference is that window.onload is not cross-browser compatible, whereas document.ready(), like jQuery, works fine on all browsers.
60. Talk about for-in loops
Properties for looping objects:
for (var item in object
Copy the code
61. Talk about anonymous functions in JavaScript
Functions declared without any named identifiers are generally inaccessible to anonymous functions after declaration.
var da = function() {
console.log('dadaqianduan.cn')
}
da();
Copy the code
62. Talk about event bubbling
Click on the child handler, and the parent handler does the same.
Understanding the event bubbling mechanism?
The execution sequence of the event flow, capture phase – target phase – bubble phase. Bubbling from the inside out.
, the event defined on the div, when I click on the span it will trigger the event bound on the span, and then it will trigger the event on the outside div, and that’s bubbling.
The bubbling phase is the process from the target to the Window object. Events are bubbling by default. When the parent element adds a listening event, an event on the parent element is triggered when the child element is clicked. This is a typical bubbling.
63. JavaScript function arguments is an array
It is just an array-like object and has no array methods.
64. What is a constructor and how is it different from a normal function
The constructor is used to initialize the object when it is created. Try with new. The constructor name in the statement that creates the object must be exactly the same as the class name.
- Constructors can only be called by the new keyword
- Constructors create instantiated objects
- A constructor is the hallmark of a class
65. Tell us the difference between split() and join()
split()
Method is used to cut into an arrayjoin()
The method is to convert an array to a string
"abcdef".split("") // ["a", "b", "c", "d", "e", "f"] "abcdef".split() // ["abcdef"] "2:3:4:5".split(":",3) // ["2", "3", "4"] [1, 2, 3, 4, 5]. The join () / / "1, 2, 3, 4, 5" [1, 2, 3, 4, 5]. Join (' : ') / / "syntactic sugar for 1:2:3:4:5"Copy the code
Talk about your understanding of prototype chain
Every JavaScript object inherits another parent object, called a prototype object.
Prototype chains are almost a prerequisite for front-end interviews
Each instance object has a private __proto__ attribute pointing to its constructor’s prototype object, which also has a private __proto__ attribute as an instance object, cascading up until an object’s prototype object value is null.
When accessing an object’s attribute or method, the JS engine will first look for whether the object itself contains it. If not, it will look for the prototype object pointed to by the __proto__ attribute of the object. If not, it will continue to look up one layer until the __proto__ value of an object is null, which is the prototype chain.
In JS, each constructor has a Prototype property that points to another object, indicating that all properties and methods of the entire object are owned by the constructor.
function Person (name, age) {
this.name = name
this.age = age
}
console.log(Person.prototype)
Person.prototype.type = 'it'
Person.prototype.sayName = function () {
console.log(this.name)
}
var p1 = new Person('jeskson', 18);
var p2 = new Person('dada', 18);
console.log(p1.sayName === p2.sayName) // => true
Copy the code
Constructor Person:
Prototype --> Create a Person instance from the constructor --> __proto__ prototype object --> mystery objectCopy the code
Each constructor has a Prototype property, which is an Object.
Constructor objects have a default constructor property that points to the function of the Prototype object.
Constructor instance objects contain a pointer to the constructor’s prototype object __proto__
console.log(obj.__proto__);
console.log(obj.prototype);
console.log(obj.__proto__ === Object.prototype);
Copy the code
- The prototype constructor points to the prototype
- Constructor, New instantiates (instance object), from which (.constructor) points to the constructor
- Instance objects
(. __proto__)
Pointing to the prototype
__proto__=== 2. Constructor === 3. Constructor. Prototype === prototypeCopy the code
67. What is the difference between typeof and Instanceof
Typeof is a unary operation that returns a string indicating the typeof operand.
Instanceof, which determines whose instance the object is
The instanceof operator tests whether an object has a constructor’s prototype property in its prototype chain. Instanceof can only be used for objects and functions, not strings and numbers
GetDataType (obj) {if (obj === null) {return "null"; } else if (typeof obj === "object") {if (obj instanceof Array) {return "Array"; } else {return "object"; } } else { return typeof obj; }}Copy the code
Talk about the flow of events
The event stream is the order in which events are received from the page.
69. Talk about event capture
Events are received earlier by less specific elements and last by the most specific nodes.
70. What is a callback function
It is simply a function called through a function pointer.
71. What is a self-executing function, what are its application scenarios, and what are its benefits
Self-executing function refers to a declared anonymous function, which can call the entire anonymous function immediately. It is generally used in frameworks, plug-ins and other scenarios. The advantage is to avoid conflicts of various JavaScript libraries, isolate scope, and avoid pollution.
72. What is event delegation and what are its benefits
Event delegate is to use the bubbling principle, add the event to the parent level, trigger the execution effect. The benefits are reduced event count, improved performance, and memory leakage avoidance.
73. What is cast and what is implicit casting
There are two ways to cast data types in JavaScript: implicit and cast (also known as explicit casting).
Implicit type conversion:
== only does the value judgment, the actual implicit type conversion, and then the comparisonCopy the code
Cast:
ParseInt () converts a string to a numeric integer parseFloat() converts a string to a floating point Number() can only convert purely numeric characters to numbersCopy the code
74. What is NaN, what is its type, and how can you reliably tell if a value is equal to NaN
NaN means “not a Number,” but it is of type Number, and NaN is false when compared to anything, even itself.
75. What is cross-domain
In A broad sense, cross-domain access refers to cross-domain access, which simply means that the javascript code of website A tries to access website B, including submission capacity and content acquisition capacity. For security reasons, cross-domain access is disabled by default by all major browsers.
Cross-domain refers to the mutual access between different domain names.
76. In YYYY-MM-DD format, print the date of the day, for example, 1 January 2020, then print 2020-01-01
var d = new Date();
var year = d.getFullYear();
var month = d.getMonth() + 1;
month = month < 10 ? "0" + month : month;
var day = d.getDate();
daty = day<10? "0"+day : day;
console.log(year+'-'+month+'-'+day);
Copy the code
77. Use JavaScript to randomly pick 10 numbers between 10 and 100, store them in an array and sort them
var isArray = [];
function getRandom(start, end) {
return Math.floor(Math.random() * (end-start+1) + start)
}
for(var i = 0; i<10; i++){
isArray.push(getRandom(10,100))
}
isArray.sort()
console.log(isArray)
Copy the code
78. To implement a function clonoe, it is possible to make value (deep) copies of the five main data types in JavaScript (Number, String, Object, Array, Boolean).
function clone(obj) { var buf; if(obj instanceof Array) { var i = obj.lenght; buf = []; while(i--) { buf[i] = clone(obj[i]) } return buf; }else if(obj instanceof Object) { buf = {}; for(var i in obj) { buf[i] = clone(obj[i]) } return buf; }else{ return buf = obj; }}Copy the code
79. How do I eliminate duplicate elements in an array
function noRepeat(arr) {
var i = 0,
len = arr.length,
obj = {},
result = [];
while(++i < len) {
obj[arr[i]] || result.push(arr[i])
obj[arr[i]] = true;
}
return result;
}
Copy the code
80. Describe the DOM object query methods in 3
getElementById()
Lookup by element IDgetElementsByTagName(tag)
Search by label namegetElementsByName(name)
Lookup by element name
81. Introduce yourself with object-oriented JavaScript code
function Person(name, job, site) {
this.name = name;
this.job = job;
this.site = site;
}
Person.prototype = {
getName: function() {
console.log('my name'+this.name);
}
getJob: function() {
console.log('my job'+ this.job);
}
getWork: function() {
console.log('my work' + this.site);
}
}
var da = new Person('dada', 'it', 'shenzheng');
da.getName();
da.getJob();
da.getWork();
Copy the code
82. What is a variable scope
Variable scope, the range of availability of a variable. In general, the name used in a piece of program code is not always valid, and the scope of the code that defines the name’s availability is the scope of the name. The use of scope can improve the program logic locality, enhance the reliability of the program, reduce name conflicts. From the perspective of scope, variables can be divided into global variables and local variables.
83. How does inheritance work in JavaScript
- In a child constructor, the constructor of the parent class is executed in the scope of the child class
- In the prototype of a subclass, the property methods on the parent class constructor prototype are copied
How JavaScript implements inheritance (six ways)
1. Stereotype chain: Use stereotypes to make one reference type inherit the properties and methods of another.
Prototype chain implementation inheritance example:
function SuperType() { this.property = true; } SuperType.prototype.getSuperValue = function() { return this.property; } function SubType() { this.property = false; } // SuperType subtype.prototype = new SuperType(); SubType.prototype.getSubValue = function (){ return this.property; } var instance = new SubType(); console.log(instance.getSuperValue()); //trueCopy the code
2. Borrow constructors: Call the superclass constructor inside the subtype constructor, which can be executed on the newly created object by using the call() and apply() methods.
function SuperType() { this.colors = ["red","blue","green"]; } function SubType() { SuperType.call(this); Var instance1 = new SubType(); instance1.colors.push("black"); console.log(instance1.colors); //"red","blue","green","black" var instance2 = new SubType(); console.log(instance2.colors); //"red","blue","green"Copy the code
3. Combinatorial inheritance: An inheritance pattern that combines a chain of stereotypes and techniques borrowed from constructors to take advantage of the best of both.
function SuperType(name) { this.name = name; this.colors = ["red","blue","green"]; } SuperType.prototype.sayName = function() { console.log(this.name); } function SubType(name, age) { SuperType.call(this,name); // This. Age = age; } // subtype.prototype = new SuperType(); Subtype.prototype.constructor = Subtype; Subtype.prototype.sayAge = function() { console.log(this.age); } var instance1 = new SubType("da",18); instance1.colors.push("black"); consol.log(instance1.colors); //"red","blue","green","black" instance1.sayName(); //"EvanChen" instance1.sayAge(); //18 var instance2 = new SubType("dada",20); console.log(instance2.colors); //"red","blue","green" instance2.sayName(); //"dada" instance2.sayAge(); / / 20Copy the code
4. Old-style inheritance: Stereotypes allow you to create new objects based on existing objects without having to create custom types.
5. Parasitic inheritance: Create a function that simply encapsulates the inheritance process, enhances the object internally in some way, and then returns the object as if it really did all the work.
6. Parasitic combinatorial inheritance: inherits properties by borrowing functions and inherits methods through a hybrid form of prototype chains
84. Explain your understanding of scope chains
The scope chain corresponds to the function execution stack. The JS runtime environment is divided into global, function and Eval. Whenever code execution enters a new runtime environment, the execution context of the environment will be pushed onto the stack, and when it exits the stack, it will be removed from the stack, forming a nested relationship from the top to the bottom of the stack from the inner layer to the outer layer.
The lexical environment created by the execution context holds the reference of the lexical environment of the outer execution context. When the JS engine cannot find the corresponding variable in the current lexical environment, it will search out layer by layer, and the linked list formed in this way is the scope chain.
Scope chain refers to the rule of searching variables during code execution. First, the code searches for variables in the current scope. If the code fails to find variables, the code searches for variables in the higher scope, and the code searches for variables in the global environment
85. Talk about prototype chains in JavaScript
Each object in JavaScript has a prototype property called a prototype, and the value of a prototype is also an object, so it has its own prototype. This creates a prototype chain whose header is Object, whose Prototype is special and has a null value.
__proto__ is the actual object used to parse methods in the lookup chain, etc. Prototype uses the following command __proto__ to build the object new when creating the object:
(new Foo).__proto__ === Foo.prototype;
(new Foo).prototype === undefined;
Copy the code
Prototype is the property of the Function object; it is the prototype of the object constructed by the Function.
__proto__ is an internal property of an object that points to its prototype. The object.getProtoTypeof (o) method is currently provided, although in fact the standard __proto__ is faster.
You can use instanceof to find relationships by comparing function Prototype to the object’s __proto__ chain, or you can break those relationships by making changes.
function Point(x, y) {
this.x = x;
this.y = y;
}
var myPoint = new Point();
// the following are all true
myPoint.__proto__ == Point.prototype
myPoint.__proto__.__proto__ == Object.prototype
myPoint instanceof Point;
myPoint instanceof Object;
Copy the code
86. Tell me three ways to define a function
- Have reference function
- No arguments function
- An empty function
1. Function declarations 2. Function expressions 3. Function constructors, parameters must be quoted 4
Function da() {} var da = function() {} var da = new function();Copy the code
87. What is a global object in JavaScript and how to call it
Global properties and functions are available for all built-in JavaScript objects. By default, this refers to window, and properties and methods of the default global object can be called without having to prefix window.
Top-level functions (global functions) :
DecodeURI () decodes an encoded URI. DecodeURIComponent () decodes an encoded URI component. EncodeURI () encodes a string as a URI. EncodeURIComponent () encodeURIComponent() encodes strings as URI components. Escape () encodes the string. Eval () evaluates a JavaScript string and executes it as script code. GetClass () returns a JavaClass of a JavaObject. IsFinite () checks whether a value isFinite. IsNaN () checks if a value is a number. Number() converts the value of an object to a Number. ParseFloat () parses a string and returns a floating point number. ParseInt () parses a string and returns an integer. String() converts the value of an object to a String. Unescape () decodes the string encoded by escape().Copy the code
Top-level properties (global properties)
Infinity stands for positive Infinity. Java represents a JavaPackage at the Java.* package level. NaN indicates whether a value is a numeric value. Packages root JavaPackage object. Undefined indicates an undefined value.Copy the code
88. Talk about a few common JavaScript built-in objects and point out their advantages
Commonly used objects are Array, Date, regular expression, string, and Global
Concat () : To combine several arrays into one array. Join () : Returns a string value containing all the elements of the joined array separated by the specified delimiter. Pop () : Removes the last element of the array. Shift () : Removes the first element in the array. Slice (start, end) : Returns a segment of an array. Push () : Adds a new element to the array and returns the latest length. Sort () : Sort the array. Reverse () : Reverses the sort of the array. toLocaleString(); The current system time is displayed. Ceil () : rounded up. Floor (): round down. Round (): round. Random (): selects a random number. Get /setDate() : Returns or sets the date. Get /setFullYear(): Returns or sets the year as a four-digit number. Get /setYear(): Returns or sets the year. Get /setMonth(): Returns or sets the month. 0 is one month. Get /setHours(): returns or sets hours. In 24-hour system, get/setMinutes(): returns or sets minutes. Get /setSeconds(): Returns or sets the number of seconds. Get /setTime(): Returns or sets the time in milliseconds.Copy the code
89. What is DOM and what are the three types of DOM
DOM, Document Object Model. DOM is a W3C (World Wide Web Consortium) standard that defines standards for accessing HTML and XML documents. According to W3C standards, DOM is a platform – and language-independent interface that allows programs and scripts to dynamically access and update the content, structure, and style of documents.
There are three kinds:
- Core DOM, the standard model for any structured document
- XML Dom, the standard model for XML documents
- HTML Dom, the standard model for HTML documents
90. Talk about cookie compatibility, disadvantages, etc
91. Talk about the difference between stacks and queues
- Queues are fifo and stacks are fifO
- Both stacks and queues are linear tables, both are linear tables that limit insertion and deletion points, and both can only be inserted and deleted at the end of a linear table
92. Tell us the difference between cookies and sessions
- Cookie data is stored on the client’s browser, and session data is stored on the server
- Cookies are not very secure
- The session stays on the server for a certain period of time, which deteriorates the server performance.
- Sessions are commonly used for user authentication
- Sessions can be stored in files, databases, or memory
- Cookies and sessions are Session technologies
- There is a limit on the size of cookies and a limit on the number of cookies that can be stored by the browser, so there is no limit on the size of sessions depending on the memory size of the server
I’m Jeskson, thanks for your talent: likes, favorites and comments, and we’ll see you next time!
This article is constantly updated, you can search “Programmer Doraemon” on wechat for the first time to read, reply [information] I prepared the first line of large factory materials, this article www.dadaqianduan.cn/#/ has been included, welcome Star.
XXX | creator training camp The campaign is under way…