96 basic front-end JS interview questions (including answers)

hzc
Release: 2020-09-01 15:39:36
forward
6320 people have browsed it

[Related recommendations:Front-end interview questions

1. Several basic data Type? Complex data type? Value type and reference data type? Stack data structure?

Basic data types: Undefined, Null, Boolean, Number, String
Value type: Numeric, Boolean, null, undefined.
Reference type: object, array, function.
Stack data structure: It is a collection that supports last-in-first-out (LIFO), that is, the data inserted later is taken out first!
The following methods are provided in the js array to make it easy for us to implement the stack :
shift: Delete the first element from the array and return the value of this element.
unshift: Add one or more elements to the beginning of the array and return the new length
push: Add elements to the end of the array and return the new length
pop: Remove the last element from the array Removes an element and returns the value of this element.

2. Declaring function promotion? What is the difference between declaring a variable and declaring a function?

(1) Variable declaration promotion: variable declaration before entering The execution context is complete.
As long as a variable is declared in the code, no matter where it is declared, the js engine will place its declaration at the top of the scope;

(2) Function declaration promotion: execution The function declaration is read before the code, which means that the function declaration can be placed after the statement that calls it.
As long as the function is declared in the code, no matter where it is declared, the js engine will place its declaration at the top of the scope;

(3) Variable or function declaration: Function declarations override variable declarations, but not variable assignments.
The same name identifies a, that is, there is a variable declaration var a, and a function declaration function a() {}. Regardless of the order of the two declarations, the function declaration will overwrite the variable declaration, that is, the value of a at this time is the declared function function a() {}. Note: If a is initialized at the same time as the variable is declared, or a is assigned a value later, the value of a at this time is the value of the variable. eg: var a; var c = 1; a = 1; function a() { return true; } console.log(a);

3. Determine the data type?

The types returned by typeof are all in the form of strings, which can be used to determine the type of function; it is more convenient to determine objects of type other than Object.
Method to determine known object type: instanceof, which must be followed by the object type, and the case cannot be wrong. This method is suitable for some conditional selection or branching.

4. Asynchronous programming?

Method 1: Callback function. The advantage is that it is simple, easy to understand and deploy. The disadvantage is that it is not conducive to reading and maintaining the code. The various parts are highly coupled (Coupling), and the process will be very complicated. Confusing, and only one callback function can be specified per task.

Method 2: Time monitoring, multiple events can be bound, each event can specify multiple callback functions, and can be "decoupled" (Decoupling), which is conducive to modularization. The disadvantage is that the entire program has to become event-driven, and the running process will become very unclear.

Method 3: Publish/subscribe, similar in nature to "event listening", but obviously better than the latter.

Method 4: Promises object is a specification proposed by the CommonJS working group to provide a unified interface for asynchronous programming.
Simply put, the idea is that each asynchronous task returns a Promise object, which has a then method that allows a callback function to be specified.

5. Event flow? Event capture? Events bubbling up?

Event flow: The order in which events are received from the page. That is to say, when an event occurs, the propagation process of this event is the event flow.

The event stream in IE is called event bubbling; event bubbling: the event is initially received by the most specific element, and then propagated upwards to less specific nodes (documents). For HTML, when an element generates an event, it will pass the event to its parent element. After the parent element receives it, it will continue to pass it to its upper-level element, and then it will be propagated to the document. Object (Personally tested the current browser to window object, only IE8 and below are not like this

Event capture is that less specific elements should receive events earlier, and the most specific nodes should receive events last. Their intention is to capture the event before it reaches the target; that is, it is exactly the opposite of the bubbling process. Taking the click event of HTML as an example, the document object (DOM-level specification requires that the propagation starts from the document, but current browsers start from the document). The window object (beginning with the window object) first receives the click event, and then the event propagates downward along the DOM tree until it reaches the actual target of the event;

6. How to clear a timer?

window.clearInterval();
window.clearTimeout();

7. How to add a dom object to the body? What is the difference between innerHTML and innerText?

body.appendChild(dom element);
innerHTML: All content from the starting position to the ending position of the object, including Html tags.
innerText: Content from the starting position to the ending position, but it removes the Html tag
Briefly describe the five window objects and attributes respectively

Member objects
window.event window.document window .history
window.screen window.navigator window.external
The properties of the Window object are as follows:
window //Window itself
window.self //Reference this window window=window.self
window.name //Name the window
window.defaultStatus //Set the window status bar information
window.location //URL address, equipped with this attribute, you can open a new page

8. Data persistence technology (ajax)? Briefly describe the ajax process

1) Client generates js events
2) Create XMLHttpRequest object
3) Respond to XMLHttpRequest Configure
4) Send an asynchronous request through the AJAX engine
5) The server receives the request and processes the request, returning html or xml content
6)XML calls a callback() to process the response content
7) Partial page refresh

9. Callback function?

The callback function is a function called through a function pointer. If you pass a function pointer (address) as a parameter to another function, and when this pointer is used to call the function it points to, we say it is a callback function. The callback function is not called directly by the implementer of the function, but is called by another party when a specific event or condition occurs to respond to the event or condition.

10. What is a closure?* What is the difference between Stack Overflow and Stack Overflow? Memory leak? What operations can cause memory leaks? How to prevent memory leaks?

Closure: It is a function that can read the internal variables of other functions.
Stack overflow: regardless of the size of the local data block allocated in the stack, too much data is written to the data block, causing the data to go out of bounds and overwriting other data. Often happens with recursion.
Memory leak refers to: using dynamic storage to allocate function memory space, which is not released after use, resulting in the memory unit being occupied all the time. until the program ends. Refers to any object that survives after you no longer own or need it.

Causing memory leaks:
If the first parameter of setTimeout uses a string instead of a function, it will cause a memory leak.
Closure, console log, loop (when two objects refer to each other and retain each other, a loop will be generated)
Prevent memory leaks:
1. Do not bind events dynamically;
2. Do not bind events to DOM that is dynamically added or dynamically removed. Use events to bubble up in the parent container to listen for events;
3. If you want to violate the above principles, you must provide a destroy method to ensure that the DOM is removed. Backbone events have also been removed. You can refer to Backbone's source code for this, which is better;
4. Singletonization, less DOM creation and less event binding.

11. How to interact with data in daily work? How to develop if the background does not provide data? What should I do if the mock data does not agree with the format returned by the background?

The backend writes interface documents, provides data interface implementation, and the frontend realizes data interaction through ajax access;
If there is no data, look for the backend to provide static data or define mock data by yourself;
The returned data is not uniform When writing a mapping file to map the data.

12 Briefly describe the ajax execution process

基本步骤:var xhr =null;//创建对象 if(window.XMLHttpRequest){ xhr = new XMLHttpRequest();}else{ xhr = new ActiveXObject("Microsoft.XMLHTTP");}xhr.open(“方式”,”地址”,”标志位”);//初始化请求 xhr.setRequestHeader(“”,””);//设置http头信息 xhr.onreadystatechange =function(){}//指定回调函数 xhr.send();//发送请求
Copy after login

13. Self-executing function? What scenarios is it used for? Benefits?

Self-executing function: 1. Declare an anonymous function 2. Call the anonymous function immediately.
Function: Create an independent scope.

Benefits: Prevent variables from spreading to the global world to avoid conflicts with various js libraries. Isolate the scope to avoid contamination, or truncate the scope chain to avoid closures that prevent reference variables from being released. Utilize the immediate execution feature to return the required business functions or objects, avoiding the need to deal with conditional judgments every time

Scenarios: generally used in scenarios such as frameworks and plug-ins

14.html and What is the difference between xhtml?

HTML is a basic WEB web page design language, and XHTML is a markup language based on XML.
1.XHTML elements must be nested correctly.
2.XHTML elements must be closed.
3. Tag names must use lowercase letters.
4. Empty tags must also be closed.
5.XHTML documents must have a root element.

15. What is a constructor? What is the difference from ordinary functions?

构造函数:是一种特殊的方法、主要用来创建对象时初始化对象,总与new运算符一起使用,创建对象的语句中构造函数的函数名必须与类名完全相同。
与普通函数相比只能由new关键字调用,构造函数是类的标示

16. 通过new创建一个对象的时候,函数内部有哪些改变

function Person(){}Person.prototype.friend = [];Person.prototype.name = '';// var a = new Person();// a.friend[0] = '王琦';// a.name = '程娇';// var b = new Person();// b.friend?// b.name?
Copy after login
1、创建一个空对象,并且 this 变量引用该对象,同时还继承了该函数的原型。
2、属性和方法被加入到 this 引用的对象中。
3、新创建的对象由 this 所引用,并且最后隐式的返回 this 。

17.事件委托?有什么好处?

(1)利用冒泡的原理,把事件加到父级上,触发执行效果
(2)好处:新添加的元素还会有之前的事件;提高性能。

18.window.onload ==? DOMContentLoaded ?

一般情况下,DOMContentLoaded事件要在window.onload之前执行,当DOM树构建完成的时候就会执行DOMContentLoaded事件,而window.onload是在页面载入完成的时候,才执行,这其中包括图片等元素。大多数时候我们只是想在DOM树构建完成后,绑定事件到元素,我们并不需要图片元素,加上有时候加载外域图片的速度非常缓慢。

19.节点类型?判断当前节点类型?

1. 元素节点
2. 属性节点
3. 文本节点
8. 注释节点
9. 文档节点
通过nodeObject.nodeType判断节点类型:其中,nodeObject 为DOM节点(节点对象)。该属性返回以数字表示的节点类型,例如,元素节点返回 1,属性节点返回 2 。

20.如何合并两个数组?数组删除一个元素?

//三种方法。 (1)var arr1=[1,2,3]; var arr2=[4,5,6]; arr1 = arr1.concat(arr2); console.log(arr1); (2)var arr1=[1,2,3]; var arr2=[4,5,6]; Array.prototype.push.apply(arr1,arr2); console.log(arr1); (3)var arr1=[1,2,3]; var arr2=[4,5,6]; for (var i=0; i < arr2.length; i++) { arr1.push( arr2[i] ); } console.log(arr1);
Copy after login

21.强制转换 显式转换 隐式转换?

//强制类型转换: Boolean(0) // => false - 零 Boolean(new object()) // => true - 对象 Number(undefined) // => NaN Number(null) // => 0 String(null) // => "null" parseInt( ) parseFloat( ) JSON.parse( ) JSON.stringify ( )
Copy after login
隐式类型转换:
在使用算术运算符时,运算符两边的数据类型可以是任意的,比如,一个字符串可以和数字相加。之所以不同的数据类型之间可以做运算,是因为JavaScript引擎在运算之前会悄悄的把他们进行了隐式类型转换的
(例如:x+"" //等价于String(x)
+x //等价于Number(x)
x-0 //同上
!!x //等价于Boolean(x),是双叹号)

显式转换:
如果程序要求一定要将某一类型的数据转换为另一种类型,则可以利用强制类型转换运算符进行转换,这种强制转换过程称为显示转换。
显示转换是你定义让这个值类型转换成你要用的值类型,是底到高的转换。例 int 到float就可以直接转,int i=5,想把他转换成char类型,就用显式转换(char)i

22. Jq中如何实现多库并存?

Noconfict 多库共存就是“$ ”符号的冲突。

方法一: 利用jQuery的实用函数$.noConflict();这个函数归还$的名称控制权给另一个库,因此可以在页面上使用其他库。这时,我们可以用"jQuery "这个名称调用jQuery的功能。 $.noConflict();
jQuery('#id').hide();
.....
//或者给jQuery一个别名
var $j=jQuery
$j('#id').hide();
.....

方法二: (function($){})(jQuery)

方法三: jQuery(function($){})
通过传递一个函数作为jQuery的参数,因此把这个函数声明为就绪函数。 我们声明$为就绪函数的参数,因为jQuery总是吧jQuery对象的引用作为第一个参数传递,所以就保证了函数的执行。

23.Jq中get和eq有什么区别?

get() :取得其中一个匹配的元素。num表示取得第几个匹配的元素,get多针对集合元素,返回的是DOM对象组成的数组 eq():获取第N个元素,下标都是从0开始,返回的是一个JQuery对象

24.如何通过原生js 判断一个元素当前是显示还是隐藏状态?

if( document.getElementById("div").css("display")==='none') if( document.getElementById("div").css("display")==='block') $("#div").is(":hidden"); // 判断是否隐藏 $("#div").is(":visible")
Copy after login

25.Jq如何判断元素显示隐藏?

//第一种:使用CSS属性 var display =$('#id').css('display'); if(display == 'none'){ alert("我是隐藏的!"); } //第二种:使用jquery内置选择器 

仅仅是测试所用

if($("#test").is(":hidden")){ $("#test").show(); //如果元素为隐藏,则将它显现 }else{ $("#test").hide(); //如果元素为显现,则将其隐藏 } //第三种:jQuery判断元素是否显示 是否隐藏 var node=$('#id'); if(node.is(':hidden')){  //如果node是隐藏的则显示node元素,否则隐藏   node.show();  }else{   node.hide(); }
Copy after login

26.移动端上什么是点击穿透?

点击穿透现象有3种:
点击穿透问题:点击蒙层(mask)上的关闭按钮,蒙层消失后发现触发了按钮下面元素的click事件跨页面点击穿透问题:如果按钮下面恰好是一个有href属性的a标签,那么页面就会发生跳转另一种跨页面点击穿透问题:这次没有mask了,直接点击页内按钮跳转至新页,然后发现新页面中对应位置元素的click事件被触发了

解决方案:
1、只用touch
最简单的解决方案,完美解决点击穿透问题
把页面内所有click全部换成touch事件( touchstart 、’touchend’、’tap’)

2、只用click
下下策,因为会带来300ms延迟,页面内任何一个自定义交互都将增加300毫秒延迟

3、tap后延迟350ms再隐藏mask
改动最小,缺点是隐藏mask变慢了,350ms还是能感觉到慢的

4、pointer-events
比较麻烦且有缺陷, 不建议使用mask隐藏后,给按钮下面元素添上 pointer-events: none; 样式,让click穿过去,350ms后去掉这个样式,恢复响应缺陷是mask消失后的的350ms内,用户可以看到按钮下面的元素点着没反应,如果用户手速很快的话一定会发现

27.Jq绑定事件的几种方式?on bind ?

jQuery中提供了四种事件监听方式,分别是bind、live、delegate、on,对应的解除监听的函数分别是unbind、die、undelegate、off

Bind( )是使用频率较高的一种,作用就是在选择到的元素上绑定特定事件类型的监听函数;

Live( )可以对后生成的元素也可以绑定相应的事件,处理机制就是把事件绑定在DOM树的根节点上,而不是直接绑定在某个元素上;

Delegate( )采用了事件委托的概念,不是直接为子元素绑定事件,而是为其父元素(或祖先元素也可)绑定事件,当在p内任意元素上点击时,事件会一层层从event target向上冒泡,直至到达你为其绑定事件的元素;

on( )方法可以绑定动态添加到页面元素的事件,on()方法绑定事件可以提升效率;

28.Jq中如何将一个jq对象转化为dom对象?

方法一:
jQuery对象是一个数据对象,可以通过[index]的方法,来得到相应的DOM对象。
如:var $v =$("#v") ; //jQuery对象
var v=$v[0]; //DOM对象
alert(v.checked) //检测这个checkbox是否被选中

方法二:
jQuery本身提供,通过.get(index)方法,得到相应的DOM对象
如:var $v=$("#v"); //jQuery对象
var v=$v.get(0); //DOM对象
alert(v.checked) //检测这个checkbox是否被选中

29.Jq中有几种选择器?分别是什么?

层叠选择器、基本过滤选择器、内容过滤选择器、可视化过滤选择器、属性过滤选择器、子元素过滤选择器、表单元素选择器、表单元素过滤选择器

30.Jq中怎么样编写插件?

//第一种是类级别的插件开发://1.1 添加一个新的全局函数 添加一个全局函数,我们只需如下定义: jQuery.foo = function() { alert('This is a test. This is only a test.'); }; //1.2 增加多个全局函数 添加多个全局函数,可采用如下定义: jQuery.foo = function() { alert('This is a test. This is only a test.'); }; jQuery.bar = function(param) { alert('This function takes a parameter, which is "' + param + '".'); }; 调用时和一个函数的一样的:jQuery.foo();jQuery.bar();或者$.foo();$.bar('bar');//1.3 使用jQuery.extend(object);  jQuery.extend({ foo: function() { alert('This is a test. This is only a test.'); }, bar: function(param) { alert('This function takes a parameter, which is "' + param +'".'); } }); //1.4 使用命名空间// 虽然在jQuery命名空间中,我们禁止使用了大量的javaScript函数名和变量名。// 但是仍然不可避免某些函数或变量名将于其他jQuery插件冲突,因此我们习惯将一些方法// 封装到另一个自定义的命名空间。jQuery.myPlugin = { foo:function() { alert('This is a test. This is only a test.'); }, bar:function(param) { alert('This function takes a parameter, which is "' + param + '".'); } }; //采用命名空间的函数仍然是全局函数,调用时采用的方法: $.myPlugin.foo(); $.myPlugin.bar('baz');//通过这个技巧(使用独立的插件名),我们可以避免命名空间内函数的冲突。//第二种是对象级别的插件开发//形式1: (function($){ $.fn.extend({ pluginName:function(opt,callback){ // Our plugin implementation code goes here. } }) })(jQuery); //形式2:(function($) { $.fn.pluginName = function() { // Our plugin implementation code goes here. }; })(jQuery);//形参是$,函数定义完成之后,把jQuery这个实参传递进去.立即调用执行。//这样的好处是,我们在写jQuery插件时,也可以使用$这个别名,而不会与prototype引起冲突
Copy after login

31.$('p+.ab')和$('.ab+p') 哪个效率高?

$('p+.ab')效率高

32.$.map和$.each有什么区别

map()方法主要用来遍历操作数组和对象,会返回一个新的数组。$.map()方法适用于将数组或对象每个项目新阵列映射到一个新数组的函数;
each()主要用于遍历jquery对象,返回的是原来的数组,并不会新创建一个数组。

33.编写一个 getElementsByClassName 封装函数?

  
Copy after login

34.简述下工作流程

My work process in the previous company was roughly like this: after the company's finalization meeting, a simple technical discussion would be held, and then our front-end would make advance technical preparations. The front-end cutter will cut the psd design draft and integrate the css files. We mainly write the JS part, which includes building the front-end framework (large project), writing js business and data persistence operations, we will also write js plug-ins and encapsulate them for easy use, and write JS front-end components and JS test units. Finally Integrate the completed JS part with the HTML page provided by the cutter. Finally, perform functional testing, page compatibility, and product restoration on the completed page. The product is then sealed and submitted for testing. If a BUG occurs, it will be returned to our developers for modification, and then submitted for testing. Finally, if the test is successful, the version will be archived. Wait until all programs are online to conduct online testing.

35. What version control tools are generally used? How does svn lock files?

Purpose of svn locking: To prevent multiple people from changing the same file at the same time To cover each other, the version control system must have a conflict handling mechanism.

Two strategies for svn locking: Optimistic locking: All checked-out files are readable and writable. Modifications to files do not need to obtain file locks. When you check in after modifying the file, it will first You are required to update local files. The version control system will not overwrite your local modifications, but will let you merge conflicts and check in.

Strict locking: All checked-out files are read-only. Any modification to the file must obtain a lock on the file. If others do not have a lock on the file, the version control system will authorize it. Gives you a lock on the file and makes the file editable.

Two locking steps for svn: Optimistic locking: Select the file you want to lock, then right-click the menu and click TortoiseSVN to select Get Lock.

Strict locking: Right-click on the file or directory that you want to strictly lock, use the TortoiseSVN property menu, click New Property, and select the required locking.

36. What is the difference between git and svn?

SVN is a centralized version control system. The version library is centralized on the central server. When working, They all use their own computers, so they first need to get the latest version from the central server, and then do the work. After finishing the work, they need to push the work they have done to the central server. The centralized version control system must be connected to the Internet to work. If it is on a local area network, it is okay, the bandwidth is large enough, and the speed is fast enough. If it is on the Internet, if the network speed is slow, it will be confusing.

Git is a distributed version control system, so it does not have a central server. Everyone’s computer is a complete version library. In this way, you don’t need to be connected to the Internet when working, because the versions are all on your own. on the computer. Since everyone's computer has a complete version library, how can multiple people collaborate? For example, if you have modified file A on your computer, and someone else has also modified file A on your computer, you only need to push your modifications to each other, and you can see each other's modifications.

37. What is the difference between jquery and zepto?

1. For mobile programs, Zepto has some basic touch events that can be used for touch screen interaction (tap events , swipe incident), Zepto does not support IE browser. This is not because Zepto developer Thomas Fucks was confused on the cross-browser issue, but a decision made after careful consideration in order to reduce the file size. Like the jQuery team no longer supports older versions of IE (6 7 8) in version 2.0. Because Zepto uses jQuery syntax, it recommends jQuery as a fallback library on IE in its documentation. That way the program can still run in IE, and other browsers can enjoy the file size advantage of Zepto. However, the APIs of the two are not fully compatible, so be careful and do sufficient research when using this method. test.

2. The difference between Dom operations: jQuery will not take effect when adding id, but Zepto will take effect.

3.zepto is mainly used on mobile devices and only supports newer browsers. The advantage is that the code size is relatively small and the performance is better.
jquery mainly has good compatibility and can run on various PCs and mobile phones. The advantage is that it is compatible with various browsers. The disadvantage is that the amount of code is large, and the performance is not good enough considering compatibility.

38. $(function(){}) and window.onload and $(document).ready(function(){})

window.onload: Used to run the function within the function when all elements of the page, including external reference files, images, etc., are loaded. The load method can only be executed once. If multiple ones are written in the js file, only the last one can be executed.

$(document).ready(function(){}) and $(function(){}) are both used to execute internal functions after the standard DOM elements of the page are parsed into a DOM tree. This function can be written multiple times in the js file. It has a great advantage for js written by multiple people, because all behavioral functions will be executed. Moreover, the $(document).ready() function can be executed after the HMTL structure is loaded. It does not need to wait for time-consuming work such as large file loading or non-existent connections to be completed before execution, which is highly efficient.

39. What is the difference between attr and prop in Jq

For the inherent attributes of the HTML element itself, use the prop method when processing.
For our own custom DOM attributes of HTML elements, use the attr method when processing.

40. Briefly describe the difference between this and when defining properties and methods? Prototype?

This represents the current object. If this is used in the global scope, it refers to the current page object window; if this is used in a function, what this refers to is based on the runtime of this function. What object is called on. We can also use the two global methods apply and call to change the specific pointer of this in the function.

Prototype is essentially a JavaScript object. And every function has a default prototype attribute.

The attribute methods defined on the prototype are shared by all instances. All instances refer to the same object. Modifying the attributes on the prototype by a single instance will also affect all other instances.

41. What is precompiled speech | precompiled processor?

Sass is a CSS preprocessor language that generates CSS code programmatically. Because it is programmable, it has high control flexibility and freedom, making it easy to implement some codes that are difficult to write CSS code directly.

At the same time, because Sass is a language that generates CSS, the written Sass file cannot be used directly. It must be compiled into a CSS file by a compiler before it can be used.

CSS preprocessor is a language used to add some programming features to CSS without considering browser compatibility issues. For example, you can use variables, simple program logic, functions, etc. in CSS Some basic skills in programming languages can make your CSS more concise, more adaptable, and the code more intuitive, among many other benefits. The most commonly used CSS preprocessors are sass, less css, and stylus.

42.ajax and jsonp?

The difference between ajax and jsonp:
Similar points: both request a url
Differences: The core of ajax is to obtain content through xmlHttpRequest
The core of jsonp is dynamic addition
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!