search
HomeWeb Front-endJS TutorialTake a look at these front-end interview questions to help you master high-frequency knowledge points (6)

Take a look at these front-end interview questions to help you master high-frequency knowledge points (6)

10 questions every day, after 100 days, you will have mastered all the high-frequency knowledge points of front-end interviews, come on! ! ! , while reading the article, I hope you don’t look at the answers directly, but first think about whether you know it, and if so, what is your answer? Think about it and then compare it with the answer. Would it be better? Of course, if you have a better answer than mine, please leave a message in the comment area and discuss the beauty of technology together.

Interviewer: Could you please briefly describe the differences between var, let, and const?

Me: Uh~, okay, the differences between the three functions are summarized as follows:

var: The most commonly used variables; Repeated declarations are allowed, but data will be overwritten; variable promotion will occur; local variables are mounted on global objects, which will cause pollution of the global object.

console.log(a) // 因变量提升, var a;提到前面但是没有赋值,所以值为undefined
var a = 1
var a = '你好' // var声明的变量会被重新赋值
console.log(a) // a会打印被重新赋值的值
console.log(window.a) // var声明的局部变量会被挂载到全局变量上,造成全局变量的污染。

let: es6 new command, usage is similar to var; repeated declarations are not allowed; there is no variable promotion; often acts on block-level scope to avoid local Variables cause pollution of global variables.

let a=10;
console.log(a) // 不存在变量提升,所以值为:10
console.log(window.a) // 不会造成全局污染,所以值为 undefined
for(let i =0;i<p><span style="color:#be191c;"><strong>const</strong></span>: es6 new command, used to declare constants and the values ​​cannot be modified; declared constants must be initialized immediately, otherwise an error will be reported when assigning values ​​later; repeated declarations are not allowed ;const points to the address of the variable. As long as the address referenced by the variable name remains unchanged, no error will be reported</p><pre class="brush:php;toolbar:false">const arr = ['小张','小王','小李','小赵']
arr[0]='小明'
console.log(arr) // ['小明', '小王', '小李', '小赵']
const arr = [] // 报错

Interviewer: Please talk about your understanding of deep copy and shallow copy

Me: Uh~, okay, the understanding of the two is summarized as follows:

Deep copy: New data and original data do not interfere with each other.

// 扩展运算符在一维数组中是属于深拷贝,在多维数组中属于浅拷贝
let arr = [1,2,3]
let newArr = [...arr]
newArr.push(4)
console.log(arr,newArr) // [1, 2, 3],[1, 2, 3, 4]

// 深拷贝用法
let list = [
    {id:1,name:'张三',age:18},
    {id:2,name:'李四',age:28},
    {id:3,name:'王五',age:38},
]
let newList = JSON.parse(JSON.stringify(list))
newList.pop()
console.log(list.length,newList.length) // 3 2

Of course, there is also a standard way of writing deep copy, as follows:

// 标准的深拷贝 => 引用数据类型(数组,对象)
function deepClone(source){
    const targetObj = source.constructor === Array ? [] : {}
    for(let keys in source){
        if(source.hasOwnProperty(keys)){
            // 引用数据类型
            if(source[keys] && typeof source[keys] === 'object'){
                targetObj[keys] = source[keys].constructor === Array ? [] : {}
                // 递归
                targetObj[keys] = deepClone(source[keys])
            }else{
                // 基本数据类型,直接赋值
                targetObj[keys] = source[keys]
            }
        }
    }
    return targetObj
}

let obj = {
    name:'张三',
    age:18,
    hobby:['抽烟','喝酒','烫头'],
    action:{
        am:'敲代码',
        pm:'睡觉'
    }
}
let newObj = deepClone(obj)
newObj.name = '李四'
console.log(obj.name,newObj.name)// 张三 李四

Shallow copy: New data will affect the original data.

let arr = [1,2,3]
let newArr = arr
// 对新数据做出改变,原数据也会发生改变,这种就叫做浅拷贝
newArr.push(4) // [1, 2, 3, 4]
console.log(arr,newArr) // [1, 2, 3, 4]

To put it bluntly, deep copy is to obtain new data and has nothing to do with the original data; although shallow copy can obtain new data, it still has a certain connection with the original data.

Interviewer: What did the browser do the moment you entered the URL?

Me: Uh~, URL consists of the following parts:

https: Transport protocol (between http and tcp Added a layer of TSL or SSL security layer)

www: Server

baidu.com: Domain name

DNS domain name system will match the real IP, the first time access Normally, the second visit will store the IP resolved by the domain name locally and use it to read the browser cache.

The moment I entered the URL I experienced: Domain name -> DNS Domain Name System -> Get the real IP -> Establish a connection (TCP three-way handshake) -> Get the data, render the page -> Wave four times

Specific implementation process:

  • 1. URL parsing: determine whether to search for content or request URL

  • 2. Find the local cache: if there is a cache, return it directly to the page. If there is no cache, it will enter the network request stage

  • 3. DNS resolution

  • 4. Establish TCP connection through three-way handshake

  • 5. Synthesize request header information and send http request

  • 6. Process the response information

  • 7. Disconnect the TCP connection by waving four times

  • 8. If the response status code is 301, then Redirect

  • 9. The browser renders the page: 1) parses the HTML and generates a DOM tree; 2) calculates the node style according to the CSS and generates a stylesheet; 3) generates a layout tree; 4) Generate independent layers for specific elements

Me: Uh~, okay, the relationship between them is as follows:

Same points:

They are all browser storage, and they are all stored locally in the browser.

Difference:

  • 1.Cookie is written by the server or front end, sessionStorage and localStorage are both written by the front end Enter

  • 2. The life cycle of the cookie is set when the server writes it. LocalStorage will always exist as long as it is written, unless it is manually cleared. SessionStorage is automatically cleared when the page is closed.

  • 3. The cookie storage space is about 4kb, and the sessionStorage and localStorage spaces are relatively large, about 5M

  • 4.3 All data sharing follows the same origin principle, and sessionStorage is also restricted to the same page

  • 5. When the front end sends a request to the back end, Automatically carry cookies, session and local do not carry

  • 6. Cookies generally store login verification information or tokens. LocalStorage is often used to store data that is not easy to change and reduce server pressure. SessionStorage can be used Monitor whether the user refreshes to enter the page, such as the music player to restore the progress bar function

Interviewer: What are the JS data types and what are the differences?

Me: Uh~, JS data types are divided into two categories: one is basic data type, the other is reference data type, as follows:

  • Basic types: string, number, boolean, null, undefined, symbol, bigInt

  • Reference type: object, array

Basic types are stored in the stack, with small space and frequent operations

Reference types are stored in the heap, with large space, and are stored in the stack The pointer points to the starting address in the heap

Note: Symbol is unique and cannot be enumerated. Use getOwnPropertySymbols to obtain

Interviewer: Tell me about your understanding of closures?

Me: Uh~, the inner function refers to the variables in the outer function, and the set of these variables is the closure.

  • Principle of formation: Scope chain, the current scope can access variables in the superior scope.

  • Problem solved: It can prevent the variables in the function scope from being destroyed after the function execution ends, and it can also be used in the function Local variables inside the function can be accessed from the outside. Problems caused by

  • : Since the garbage collector will not destroy the variables in the closure, a memory leak occurs. If the leakage accumulates too much, it will easily lead to memory overflow.

  • Application of closure, can imitate block-level scope, can achieve currying, define privileged methods in the constructor, Closures, etc. are used in data responsive Observer in Vue.

Interviewer: How many methods does JavaScript have to determine the type of a variable?

Me: Uh~, okay, the summary is as follows:

1. typeof (based on binary judgment), cannot determine the data type: null and object

2 . intanceof (judged based on the prototype chain), the native data type cannot be judged

3. constructor.name (judged based on the constructor), the null data type cannot be judged

4. Object.prototype.toString .call() (use the toString method of Object to judge) all types of data can be judged. Remember that the judgment result is printed as: '[object Xxx]'

Interviewer: Let’s talk about null and undefined The difference, how to make a property null

Me: Uh~, null is defined and assigned null undefined is defined but not assigned.

Interviewer: Tell me about any methods to maintain real-time communication between the front and back ends?

Me: Uh~, polling, long polling, iframe streaming, WebSocket, SSE.

Interviewer: Tell me the difference between pseudo array and array?

Me: Uh~, okay, the summary is as follows:

Characteristics of pseudo arrays: The type is object, arrays cannot be used Methods, you can get the length, you can use for in to traverse

Pseudo arrays canConvert to arrays: Array.prototype.slice.call(), Array. from(), [...pseudo array]

There areWhich are pseudo arrays: function parameters arguments, Map and Set keys(), values( ) and entires()

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of Take a look at these front-end interview questions to help you master high-frequency knowledge points (6). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools