7

Summary of questions: 160ed40803e030 https://segmentfault.com/a/1190000040189169

Question 1, before ++, after ++, difference?

var i=2 ;
a = i++ //将i的值赋给a , 即a = i,之后再执行i = i + 1;   2
a = ++i //将i+1 的值赋给a,即a = i + 1 ,之后再执行i = i + 1;   3
console.log(a)

【to sum up】:

The former ++ is calculated after the addition, and the latter ++ is calculated after the addition.

1: Pre-++ is to assign the value after +1 to the variable, and at the same time add 1 to itself;

2: Post ++ is to assign its own value to the variable, and then add 1 to itself;

What data types does

Js common data type undefined null boolean number string
Js reference type object Array function
ES6 basic data type more symblo

js judgment type?

1、typeof
Null and array cannot be detected, and the result is object, so typeof is often used to detect basic types
2、instanceof
Cannot detect number, boolean, string, undefined, null, symbol types, so instancof is often used to detect complex types and hierarchical relationships
3、constructor
There is no construstor method for null and undefined, so the constructor cannot judge undefined and null. But the direction of contructor can be changed, so it is not safe
4、Object.prototype.toString.call
All types can be judged

data types how to detect

1、typeof
例:console.log(typeof true) // boolean

2、instanceof
例:console.log([1,2] instanceof Array) // true

3、constructor
例: console.log([1, 2].constructor === Array) // ture

4、Object.prototype.toString.call
例:Object.prototype.toString.call([1, 2]) // [object Array]

Js array method

join() convert an array to a string
add at the end of push()
pop() tail delete
shift() delete head
unshift() header addition
sort()sort
reverse() reverse
concat() link two or more arrays
slice()
  var arr=[1,2,3,4,5]
console.log(arr.slice(1)) //[2,3,4,5] select a new array consisting of all elements with sequence numbers from 1 to the end
console.log(arr.slice(1,3)) //[2,3] does not contain the sequence number, the sequence number is 3
splice()
  splice(index,howmany,item1,...itemx)
index parameter: required, integer, specify the position of addition or deletion, use a negative number, specify the position from the end of the array
howmany parameter: required, the number to be deleted, if it is 0, the item will not be deleted
item1,...itemx parameters: optional, new items added to the array
  var arr=[1,2,3,4,5]
console.log(arr.splice(2,1,"hello"));//The new array returned by [3]
  console.log(arr);//[1,2,"hello",4,5]
indexOf() and lastIndexOf() (new in ES5)
forEach() (new in ES5)
map() (new in ES5)
filter() (new in ES5)
every() (new in ES5)
some() (new in ES5)
reduce() and reduceRight() (new in ES5)

What is the difference between the Array.splice() and Array.slice() methods in

Not much to say, let’s look at the first example:

var arr=[0,1,2,3,4,5,6,7,8,9];//设置一个数组
console.log(arr.slice(2,7));//2,3,4,5,6
console.log(arr.splice(2,7));//2,3,4,5,6,7,8
//由此我们简单推测数量两个函数参数的意义,
slice(start,end)第一个参数表示开始位置,第二个表示截取到的位置(不包含该位置)
splice(start,length)第一个参数开始位置,第二个参数截取长度

Then look at the second one:

var x=y=[0,1,2,3,4,5,6,7,8,9]
console.log(x.slice(2,5));//2,3,4
console.log(x);[0,1,2,3,4,5,6,7,8,9]原数组并未改变
//接下来用同样方式测试splice
console.log(y.splice(2,5));//2,3,4,5,6
console.log(y);//[0,1,7,8,9]显示原数组中的数值被剔除掉了

Although slice and splice are both intercepted for array objects, there are still obvious differences between the two. On the function parameters, the first parameter of slice and splice is the start position of the interception, and the second parameter of slice is the end position of the interception (not included) , And the second parameter of splice (representing the length of this interception from the starting position), slice will not change the original array, and splice will directly remove the intercepted data in the original array!

slice will not change the original array, splice will change the original array

value conversion

JSON.parse() to json object
JSON.stringify() to json string
String(), toString() to string type
Number parseInt() string to numeric type
split string to array
join array to string

What is cross-domain, common cross-domain

Since the browser obtains data following the same-origin policy, when accessing non-same-origin resources, cross-domain is required. Common cross-domain methods are jsonp, a img src cors
Same-origin policy: security policy of the same protocol, port, and domain name
jsonp principle
Create script tags dynamically, use callpack callback function to get the value

function callbackFunction(){
  alert("回滚");
}
var script=document.createElement("script");
script.src="http://frergeoip.net.json/?callback=callbackFunction";

CORS principle :
When the amount of data transferred is relatively large and the get form is uncertain, cors cross-domain can be used. The principle of cors is to define a cross-domain access mechanism that allows ajax to achieve cross-domain access. Cors allows web applications on one domain to submit cross-domain Ajax requests to another domain. It's very simple to implement this function, just send a response header from the server.
Jsonp is a get form, and the amount of information it carries is limited, so cors is the best choice when the amount of information is large.

http protocol :

The http protocol defines the communication method for file transfer between the server and the client
Request resources on the server, request html css js image files, etc.
There are multiple request methods (all methods are in uppercase), and the explanation of each method is as follows:
GET (get) request to obtain the resource identified by the Request-URI-get the resource
POST (post) Append new data after the resource identified by the Request-URI---transmit the resource
HEAD (head) Request to obtain the response message header of the resource identified by the Request-URI---get the message header
PUT (put) Request the server to store a resource, and use Request-URI as its identification---update the resource
DELETE (delete) Request the server to delete the resource identified by the Request-URI --- delete the resource
TRACE (trace) Request the server to send back the received request information, mainly used for testing or diagnosis
CONNECT (connect) reserved for future use
OPTIONS (options) request to query the performance of the server, or query options and requirements related to resources
Common status codes:
200 request successful
301 Resources (webpages, etc.) are permanently transferred to other URLs
404 The requested resource does not exist
500 internal server error

HTTP status code

100 Continue Continue, generally when sending a post request, the server will return this information after the http header has been sent to indicate confirmation, and then send specific parameter information
200 OK Normal return message
201 Created request was successful and the server created a new resource
202 Accepted The server has accepted the request, but has not yet processed it
301 Moved Permanently The requested webpage has been permanently moved to a new location.
302 Found temporary redirection.
303 See Other Temporary redirection, and always use GET to request a new URI.
304 Not Modified Since the last request, the requested webpage has not been modified.
400 Bad Request The server cannot understand the format of the request, and the client should not try to initiate a request with the same content again.
401 Unauthorized The request is not authorized.
403 Forbidden access is forbidden.
404 Not Found Can not find how to match the resource with the URI.
500 Internal Server Error The most common server-side error.
503 Service Unavailable The server is temporarily unable to process the request (may be overloaded or maintained).

Tell me about your understanding of

The main purpose of using closures is to design private methods and variables. The advantage of closures is that they can avoid the pollution of global variables. The disadvantage is that closures will reside in memory and increase memory usage. Improper use can easily cause memory leaks.
Closures have three characteristics:

    1.函数嵌套函数
    2.函数内部可以引用外部的参数和变量
    3.参数和变量不会被垃圾回收机制回收

Closure use
1 cache
Imagine that we have a function object that is very time-consuming to process. Each call will take a long time. Then we need to store the calculated value. When calling this function, first look it up in the cache. If you can’t find it When it arrives, it performs calculation, then updates the cache and returns the value. If it is found, just return the value found. Closures can do exactly this, because it does not release external references, so the value inside the function can be retained.
2 Realize package
Let's first look at an example of encapsulation. The internal variables cannot be accessed outside of the person, but can be accessed by providing a closure:

var person = function(){    
    //变量作用域为函数内部,外部无法访问    
    var name = "default";              
    return {    
       getName : function(){    
           return name;    
       },    
       setName : function(newName){    
           name = newName;    
       }    
    }    
}();        
print(person.name);//直接访问,结果为undefined    
print(person.getName());    
person.setName("abruzzi");    
print(person.getName()); 

stop the event from bubbling up?

ie: stop bubbling ev.cancelBubble = true; non-IE ev.stopPropagation();

block the default event?

(1)return false;(2) ev.preventDefault();

event agent

Event delegation means that the event is bound to the parent box, and then the child box triggers the event. Due to the event bubbling, the parent box event is also triggered. At this time, in the time processing function of the parent box, you can pass the srcElement or target property To get the target time and deal with it accordingly

add, delete, replace and insert into a node?

1)创建新节点
createElement() //创建一个具体的元素
createTextNode() //创建一个文本节点
 
2)添加、移除、替换、插入
appendChild() //添加
removeChild() //移除
replaceChild() //替换
insertBefore() //插入
 
3)查找
getElementsByTagName() //通过标签名称
getElementsByName() //通过元素的Name属性的值
getElementById() //通过元素Id,唯一性

The difference between document load and document ready?

document.onload is to execute js after the structure and style, external js and image are loaded
document.ready is a method to be executed when the dom tree is created. The native species does not have this method. There is $().ready(function) in jquery

Javascript event flow models?

"Event capture": from top to bottom, window, document, document.documentelment (acquired html) document, body, ..... target element

"Event bubbling": from bottom to top: vice versa

"DOM event flow": three stages: event capture, target stage, event bubbling

image.png
Dom event class:

Dom0  element.onclick=function(){}

DOM2 element.addEventlistener(‘click’,function(){},flase)

DOM3 element.addEventlistener(‘keyup’,function(){},flase)

Event.preventdefault()  阻止默认事件

Event.stoppropagation()  阻止冒泡

Event.currenTtarget()事件代理 

Event.target 当前被点击元素

the difference between null and undefined?

Null is an object that represents "none" and is 0 when converted to a value; undefined is an original value that represents "none" and is NaN when converted to a value.

When the declared variable has not been initialized, the default value of the variable is undefined. Null is used to indicate an object that does not yet exist, and is often used to indicate that a function attempts to return an object that does not exist.

the difference and function of call() and .apply()?

Similarities: the effects of the two methods are exactly the same, both of which change the point of this

Difference: the parameters passed by the method are different

Object.call(this,obj1,obj2,obj3)

Object.apply(this,arguments)

Apply() receives two parameters, one is the scope of function operation (this), and the other is the parameter array.

The first parameter of the Call() method is the same as apply(), but the passed parameters must be listed.

mvc and mvvm mode principle:

image.png

JS distinguish between micro-tasks and macro-tasks?

(1) js is single threaded, but divided into synchronous and asynchronous
(2) Both microtasks and macrotasks are asynchronous tasks, and they all belong to a queue
(3) Macro tasks are generally: script, setTimeout, setInterval, setImmediate
(4) Micro task: native Promise
(5) When encountering a micro task, execute the micro task first. If there is no micro task after the execution, execute the next macro task. If there are micro tasks, execute the micro tasks one by one in order

setTimeout and setInterval

//setTimeout是3秒后执行
 setTimeout(function(){
 alert(123)
 },3000)

//setInterval是每隔三秒执行一次,不断的重复执行
 setInterval(function(){
 alert(1121222)
 },3000)
//两个执行都是异步进行的

deep copy shallow copy

The most fundamental difference between deep copy and shallow copy is whether to actually obtain a copy entity of an object, not a reference.

Suppose B copies A, and when A is modified, see if B changes:

If B also changes afterwards, it means that it is a shallow copy, which is short! (Modify the same value in the heap memory)

If B does not change, it means that it is a deep copy and self-supporting! (Modify different values in heap memory)
shallow copy implementation:

  var a = [1, 2, 3, 4, 5];
  var b = a;
  a[0] = 2
  console.log(a);//[2,2,3,4,5]
  console.log(b);//[2,2,3,4,5]  ////b会随着a的变化而变化

deep copy implementation:

  var a = [{"name":"weifeng"},{"name":"boy"}];
  var a_copy =[].concat(JSON.parse(JSON.stringify(a)));//深拷贝
  a_copy[1].name = "girl"
  console.log(a);//[{"name":"weifeng"},{"name":"boy"}]
  console.log(a_copy );//[{"name":"weifeng"},{"name":"girl"}]  

Rearrange and redraw

Reflow (rearrangement):
When part (or all) of the render tree needs to be rebuilt due to changes in the size, layout, and hiding of elements. This is called reflow. Each page needs to be reflowed at least once, that is, when the page is loaded for the first time, reflow will definitely occur at this time, because the render tree is to be constructed. During reflow, the browser invalidates the affected part of the rendering tree and reconstructs this part of the rendering tree. After the reflow is completed, the browser redraws the affected part to the screen. This process is called redrawing.
redraw:
When some elements in the render tree need to update attributes, and these attributes only affect the appearance and style of the element, but do not affect the layout, such as background-color. It is called redrawing.
difference:
Reflow is bound to cause redrawing, and redrawing does not necessarily cause reflow. For example: when only the color changes, only redrawing will occur without causing reflow
Reflow is required when the page layout and geometric properties change
For example: adding or deleting visible DOM elements, element position changes, element size changes-margins, padding, borders, width and height, content changes.

anti-shake and throttling?

In the process of front-end development, we often need to bind some continuously triggered events, such as resize, scroll, mousemove keyup, etc., but sometimes we don't want to execute functions so frequently during the continuous triggering of events.

How do we usually solve this situation? Generally speaking, anti-shake and throttling are better solutions.
1. Anti-shake:
Refers to the function execution after n seconds after the event is triggered. If the event is triggered again within n seconds, the function execution time will be recalculated. Application scenario (suitable for the situation where multiple events are only responded to once): add an anti-shake function to the button to prevent the form from being submitted multiple times; determine whether the scroll slides to the bottom; when performing AJAX verification for continuous input in the input box, using the function anti-shake can effectively reduce The number of requests.
Here is a scenario: Now listen to an input box, and trigger the change event after the text changes. If the keyup event is used directly, the change event will be triggered frequently. After adding anti-shake, the change event will be triggered when the user input ends or pauses.
so-called anti-shake means that the function can only be executed once within n seconds after the event is triggered. If the event is triggered again within n seconds, the function execution time will be recalculated.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <input type="text" id="input1">
</body>
<script>
    const input1 = document.getElementById('input1')
//1、不加防抖 ,会一直触发change事件
    input1.addEventListener('keyup', function(){
            console.log(input1.value)
    })

//2、简单实现防抖
    let timer = null
    input1.addEventListener('keyup', function(){
        if(timer){
            clearTimeout(timer)
        }
        timer = setTimeout(() => {
            //模拟触发change事件
            console.log(input1.value)
            //清空定时器
            timer = null
        }, 1000)
    })

//3、将防抖函数这个工具进行封装
    function debounce(fn, delay = 50){
        //timer是闭包中的,不能被别人修改
        let timer = null
        return function(){
            if(timer){
                clearTimeout(timer)
            }
            timer = setTimeout(() => {
                fn.apply(this, arguments)
                timer = null
            }, delay)
        }
    }
    input1.addEventListener('keyup', debounce(function(){ 
        console.log(input1.value)
    }, 600))
</script>
</html>

Then the anti-shake function after encapsulation is:

function debounce(fn, delay = 50){
        let timer = null  //timer是闭包中的,不能被别人修改
        return function(){
            if(timer){
                clearTimeout(timer)
            }
            timer = setTimeout(() => {
                fn.apply(this, arguments)
                timer = null
            }, delay)
        }
    }

2. Throttle:
The continuously sent event executes the function only once in n seconds. Application scenarios (suitable for a large number of events to be evenly distributed and triggered by time): DOM element drag and drop; Canvas brush function.
Here is a scene: drag and drop an element, and get to the dragged position of the element at any time. If the drag event is used directly, it will be triggered frequently, which can easily lead to freezes. After throttling is added, no matter how fast the dragging speed is, it will be triggered at regular intervals.
so-called throttling means that the event is triggered continuously but the function is executed only once in n seconds. Throttling dilutes the frequency of execution of the function.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #div1{
            border: 1px solid #ccc;
            width: 200px;
            height: 100px;
        }
    </style>
</head>
<body>
    <div id = "div1" draggable="true">可拖拽</div>
    <script>
        const div1 = document.getElementById('div1')
  
  //1、简单实现节流
        let timer = null
        div1.addEventListener('drag', function(e){
            if(timer){
                return
            }
            timer = setTimeout(() => {
                console.log(e.offsetX, e.offsetY)
                timer = null //定时器执行了,才让timer为空
            }, 1000)            
        })

  //2、将节流函数这个工具进行封装
        function throttle(fn, delay = 100){
            let timer = null
            return function(){ 
                if(timer){
                    return
                }
                timer = setTimeout(() => {
                    fn.apply(this, arguments)
                    timer = null
                },delay)
            }
        }
        div1.addEventListener('drag', throttle(function(e){ //形参e会传给throttle函数运行后返回的函数
                console.log(e.offsetX, e.offsetY)   
        },200))
    </script>
</body>
</html>

Then the throttling function after encapsulation is:

function throttle(fn, delay = 100){
            let timer = null
            return function(){ 
                if(timer){
                    return
                }
                timer = setTimeout(() => {
                    fn.apply(this, arguments)
                    timer = null
                },delay)
            }
        }

A page is entered from the URL to the page is loaded and displayed, what happened in the process?

Divided into 4 steps:
(1) When sending a URL request, regardless of whether the URL is the URL of the Web page or the URL of each resource on the Web page, the browser will start a thread to process the request, and at the same time initiate a DNS query on the remote DNS server . This enables the browser to obtain the IP address corresponding to the request.
(2) The browser and the remote Web server establish a TCP/IP connection through TCP three-way handshake negotiation. The handshake includes a synchronization message, a synchronization-response message and a response message, and these three messages are transmitted between the browser and the server. The handshake first attempts to establish communication by the client, then the server answers and accepts the client's request, and finally the client sends a message that the request has been accepted.
(3) Once the TCP/IP connection is established, the browser will send an HTTP GET request to the remote server through the connection. The remote server finds the resource and uses an HTTP response to return the resource. An HTTP response status of 200 indicates a correct response.
(4) At this time, the Web server provides resource services, and the client starts downloading resources.
After the request returns, it enters the front-end module we are concerned about
Simply put, the browser will parse HTML to generate a DOM Tree, and secondly generate a CSS Rule Tree based on CSS, and javascript can manipulate DOM based on DOM API
Details: What happened from entering the URL to receiving it in the browser?

talk about the three-way handshake strategy of TCP transmission

In order to accurately deliver the data to the target, the TCP protocol uses a three-way handshake strategy. After the data packet is sent out using the TCP protocol, TCP will not ignore the situation after the transmission, and it will definitely confirm to the other party whether the delivery is successful. The TCP flags: SYN and ACK are used in the handshake process.
The sender first sends a data packet with the SYN flag to the other party. After the receiving end receives it, it sends back a data packet with the SYN/ACK flag to show the confirmation message. Finally, the sender sends back a data packet with an ACK flag, which represents the end of the "handshake"
If an inexplicable interruption occurs at a certain stage of the handshake process, the TCP protocol will send the same data packets in the same order again.

Tell me about your understanding of semantics?

1. When you remove or lose the style, you can make the page show a clear structure
2. Conducive to SEO: Establishing good communication with search engines helps crawlers to capture more effective information: crawlers rely on tags to determine the context and the weight of each keyword;
3. It is convenient for other devices to parse (such as screen readers, blind readers, mobile devices) to render web pages in a meaningful way;
4. It is convenient for team development and maintenance, and semantics are more readable. It is an important trend of the webpage in the next step. Teams that follow W3C standards follow this standard, which can reduce differentiation

How do you optimize the files and resources of your website?

Expected solutions include:
File merging
File Minimization/File Compression
Use CDN hosting
Use of cache (multiple domain names to provide cache)
other

Please tell me three ways to reduce page load time?

1. Compress css and js files
2. Combine js and css files to reduce http requests
3. Place external js and css files at the bottom
4. Reduce dom operations and replace unnecessary dom operations with variables as much as possible

What are the ways for

Defer and async, dynamically create DOM (create script, insert into DOM, callBack after loading), load js asynchronously on demand

What are your performance optimization methods?

(For details, please see Yahoo's 14 Performance Optimization Principles).
(1) Reduce the number of http requests: CSS Sprites, JS, CSS source code compression, image size control is appropriate; webpage Gzip, CDN hosting, data caching, image server.
(2) Front-end template JS+ data, reduce bandwidth waste caused by HTML tags, front-end saves AJAX request results with variables, and operate local variables each time without request, reducing the number of requests
(3) Use innerHTML instead of DOM operations to reduce the number of DOM operations and optimize javascript performance.
(4) When there are many styles to be set, set the className instead of directly operating the style.
(5) Use less global variables and cache the results of DOM node search. Reduce IO read operations.
(6) Avoid using CSS Expression (css expression), also known as Dynamic properties.
(7) Preload the image, put the style sheet at the top, and put the script at the bottom with a timestamp.

asynchronous loading and delayed loading

1. Asynchronous loading scheme: dynamically insert script tags
2. Get the js code through ajax, and then execute it through eval
3. Add defer or async attributes to the script tag
4. Create and insert an iframe, let it execute js asynchronously
5. Lazy loading: Some js code is not needed immediately when the page is initialized, but only needed in some cases later.

The difference between GET and POST, when to use POST?

GET: generally used for information acquisition, using URL to pass parameters, there are also restrictions on the number of messages sent, generally in 2000 characters
POST: Generally used to modify the resources on the server, there is no restriction on the information sent.
The GET method needs to use Request.QueryString to get the value of the variable, while the POST method uses the Request.Form to get the value of the variable. That is to say, Get passes the value through the address bar, and Post passes the value by submitting the form.
However, in the following situations, please use POST requests:
Unable to use cache file (update the file or database on the server)
Send a large amount of data to the server (POST has no data limit)
When sending user input containing unknown characters, POST is more stable and reliable than GET

manage your project?

The early team must determine the global style (globe.css), coding mode (utf-8), etc.;
The writing habits must be consistent (for example, they are all written in inheritance style, and the single styles are written on one line);
Mark the style writer, all modules are marked in time (mark the place where the key style is called);
Mark the page (for example, the beginning and end of the page module);
CSS and HTML are stored in parallel in folders, and they must be named uniformly (for example, style.css);
JS sub-folders store the English translation named according to the JS function.

How do you optimize your code?

Code reuse
Avoid global variables (namespaces, enclosed spaces, modular mvc...)
Split the function to avoid the function being too bloated
Annotation

What is FOUC (flashing without style content)? How do you avoid FOUC?

FOUC - Flash Of Unstyled Content 文档样式闪烁
<style type="text/css" media="all">@import "../fouc.css";</style>

The @import that references the CSS file is the culprit causing this problem. IE will load the DOM of the entire HTML document first, and then import the external CSS file. Therefore, there will be a period of time between the completion of the page DOM loading and the completion of the CSS import. Internet speed and computer speed are both related.
The solution is surprisingly simple, just add a <link> or <script> element between the <head>.

website reconstruction understanding?

Website refactoring: On the premise of not changing the external behavior, simplify the structure, increase readability, and maintain consistent behavior on the front end of the website. That is to say, optimize the website without changing the UI, and maintain a consistent UI while expanding.
For traditional websites, refactoring is usually:
Change the table layout to DIV+CSS
Make the front end of the website compatible with modern browsers (for substandard CSS, such as valid for IE6)
Optimization for mobile platforms
Optimize for SEO
Aspects that should be considered for in-depth website refactoring
Reduce coupling between codes
Keep the code flexible
Write code strictly according to specifications
Design an extensible API
Replace the old framework and language (such as VB)
Enhance user experience
Generally speaking, optimization for speed is also included in reconstruction
Compress front-end resources such as JS, CSS, and images (usually resolved by the server)
Program performance optimization (such as data reading and writing)
Use CDN to accelerate resource loading
Optimization of JS DOM
File caching of HTTP server

What is graceful degradation and progressive enhancement?

Graceful degradation: Web sites can work normally in all modern browsers. If the user is using an old browser, the code will check to make sure they work properly. Due to IE's unique box model layout problem, the hacks for different versions of IE have been gracefully degraded, adding candidates for browsers that cannot support functions, so that they can be degraded in some form on the old browsers, but they will not be degraded. Completely invalidated.
Progressive enhancement: Starting from the basic functions supported by all browsers, gradually adding those only supported by modern browsers, adding extra features to the page that are harmless to the basic browser

is the difference between

The insertion and deletion operations of the stack are performed at one end, while the operation of the queue is performed at both ends.
The queue is first in, first out, and the stack is first in last out.
The stack only allows insertion and deletion at the end of the table, while the queue only allows insertion at the end of the table and deletion at the end of the table.

the difference between 160ed40803f5fc stack and heap?

Stack area (stack)-automatically allocated and released by the compiler, storing function parameter values, local variable values, etc.
Heap — Generally allocated and released by the programmer, if the programmer does not release it, it may be reclaimed by the OS when the program ends.
Heap (data structure): Heap can be regarded as a tree, such as: heap sort;
Stack (data structure): a first-in-last-out data structure.

understand the position of front-end interface engineer? What is its prospects?

The front-end is the programmer closest to the user, closer to the back-end, database, product manager, operations, and security.

1、实现界面交互
2、提升用户体验
3、有了Node.js,前端可以实现服务端的一些事情

The front-end is the programmer closest to the user. The front-end ability is to make the product evolve from 90 points to 100 points, or even better.
Participate in the project, complete the realization drawing quickly and with high quality, accurate to 1px;
Communication with team members, UI design, and product managers;
Good page structure, page refactoring and user experience;
Deal with hacks, be compatible, and write beautiful code formats;
For server optimization, embrace the latest front-end technology.

Tell me about some of the most popular things recently? Which websites do you frequently go to?

Node.js、Mongodb、npm、MVVM、MEAN、three.js,React 。
Website: w3cfuns, sf, hacknews, CSDN, MOOC, blog garden, InfoQ, w3cplus, etc.

code algorithm

array de-

var arr=[1,1,2,2,3,4,5,7,8,9,6,4,6,2,]
var arr2=[]
for(var i=0;i<arr.length;i++){
    if(arr2.indexOf(arr[i])<0){
        arr2.push(arr[i])
    }
}
console.log(arr2) 

es6 method array deduplication

let a = [1,5,6,3,8,0,5,7,0,4,2,7,5,4,5,9,22]
let b=new Set([...a])
console.log(b);
b=[...b];
console.log(b)

bubble sort

var arr=[1,3,4,6,8,0,2,5,7,4,9,2];
var temp=0;
for (var i=0;i<arr.length;i++) {
    for(var j=0;j<arr.length-i;j++){
        if(arr[j]<arr[j+1]){
            temp=arr[j+1];
            arr[j+1]=arr[j];
            arr[j]=temp;
        }
    }
}
console.log(arr)

Get the parameters in the url

//测试地址:http://www.runobb.com/jqur/dfev.html?name=xiaohong&age=22
   function showWindowHref(){
        var sHref=window.location.href;
        var args=sHref.split('?');
        if(args[1]==sHref){
            return '';
        }
        var aa=args[1].split('&');
        var obj={}
        for (var i=0;i<aa.length;i++) {
            var bb=aa[i].split('=')
            obj[bb[0]]=bb[1]
        }
        return obj;             
    }

dimensionality reduction array

//利用[].concat.apply实现降维  
    var arr=[[1,2],[3,4]];
    function Jw(obj){
        console.log(Array.prototype.concat.apply([],obj))
            return Array.prototype.concat.apply([],obj);
    }
    Jw(arr);
//如果concat方法的参数是一个元素,该元素会直接插入新数组中;如果参数是一个数组,该数组的各个元素将被插入到新数组中
    function reduceDimension(arr){
        let ret = [];
        for(let i=0;i<arr.length;i++){
            ret=ret.concat(arr[i])
        }
        console.log(ret)
        return ret;
    }
    reduceDimension(arr)  
//递归
    function reduceDimension(arr){
        let ret = [];
        let toArr = function(arr){
            arr.forEach(function(item){
                item instanceof Array ? toArr(item) : ret.push(item);
            });
        }
        toArr(arr);
        console.log(ret)
        return ret;
    }
    reduceDimension([1, 2, [3, 4, [5, 6]]])   
//flat
    let list = [1, 2, 3, [4, [5]]];
    let res = list.flat(Infinity)
    console.log(res) // [1, 2, 3, 4, 5]    

js judges the character that appears most frequently in a string, and counts this number

var str = 'asdfssaaasasasasaa';
var json = {};
for (var i = 0; i < str.length; i++) {
    if(!json[str.charAt(i)]){
       json[str.charAt(i)] = 1;
    }else{
       json[str.charAt(i)]++;
    }
};
var iMax = 0;
var iIndex = '';
for(var i in json){
    if(json[i]>iMax){
         iMax = json[i];
         iIndex = i;
    }
}
console.log('出现次数最多的是:'+iIndex+'出现'+iMax+'次');  //出现次数最多的是:a出现 9次
let string = 'kapilalipak';
const table={}; 
for(let char of string) {
    table[char]=table[char]+1 || 1;
}
// 输出
console.log(table)// {k: 2, a: 3, p: 2, i: 2, l: 2}

write a function to clear the spaces before and after the string. (Compatible with all browsers)

function trim(str) {
    if (str & typeof str === "string") {
        return str.replace(/(^s*)|(s*)$/g,""); //去除前后空白符
    }
}

How to use jquery to disable the browser's forward and backward buttons?

<script type="text/javascript" language="javascript">
$(document).ready(function() { 
     window.history.forward(1);
     //OR  
     window.history.forward(-1);  
});  
</script>

get all the checkboxes on the page? (Does not use third-party framework)

var inputs = document.getElementsByTagName("input");//获取所有的input标签对象
var checkboxArray = [];//初始化空数组,用来存放checkbox对象。
for(var i=0;i<inputs.length;i++){
  var obj = inputs[i];
  if(obj.type=='checkbox'){
     checkboxArray.push(obj);
  }
}

program to catch exception ?

try{
  
}catch(e){
  
}finally{
  
}

js sort

ascending and descending sort function sortNumber

const arr1 = [6,1,2,3,4];
function sortNumber(a,b){
     return b-a;
}
arr1.sort(sortNumber);
console.log(arr1)
// [6, 4, 3, 2, 1]

displayed in the front if it is true

const arr2 = [
            { id: 10, flag: true },
            { id: 5, flag: false },
            { id: 6, flag: true },
            { id: 9, flag: false }
];
const r = arr2.sort((a, b) => b.flag - a.flag);
console.log(r);
// [
//     { id: 10, flag: true },
//     { id: 6, flag: true },
//     { id: 5, flag: false },
//     { id: 9, flag: false }
// ]

yangyangyang
277 声望8 粉丝