The most comprehensive js and jQuery interview questions in history
js, jQuery interview questions collection
1. Data type
Basic type: except Object, String, Number, boolean, null, undefined.
Reference type: object. It contains function, Array, and Date.
Recommended related articles:The most complete collection of js interview questions in 2020 (latest)
2. Array method
join(): Convert the array to a string, with intermediate symbols
push(): Add content to the end of the array and return New length
pop(): Delete a piece of content from the end of the array, return the length
unshift(): Add content to the head of the array, return the new length
shift(): Array Delete a piece of content from the head and return the deleted content
sort(): Sort the array contents from large to small
reverse(): Reverse the array content items
concat() : Splice the array, if there is no content, copy the array content
slice(): Intercept the array, starting from the specified subscript
splice(): Delete, insert, replace;
- Delete: 2 parameters: the position of the first item to be deleted and the number of items to be deleted.
- Insertion: 3 parameters: starting position, 0 (number of items to delete), and items to insert.
- Replacement: 3 parameters: starting position, number of items to remove, and any number of items to insert.
3. String method
charAt(): Find the corresponding value based on the subscript
charCodeAt(): Use the subscript value Find the corresponding character Unicode encoding
indexOf(): Find the corresponding subscript (first occurrence) through characters
lastIndexOf(): Find the last occurrence of the subscript value through characters
slice(): Intercept a string, 2 parameters, (starting position, ending position)
split(): Split the string into an array according to the delimiter
substring(): Intercept a string, (starting position, end position)
substr(): intercept a string with a specified position and length, (starting position, length)
toLowerCase(): string Convert to lowercase
toUpperCase(): Convert the string to uppercase
trim(): Remove all spaces before and after the string
4. Prevent bubbling, prevent Default event
Prevent bubbling:
e.stopPropagation e.cancleBubble=true(IE) return false;
Prevent default event:
e.preventDefault(); e.returnValue=false;(IE) return false;
5. Function scope
Function scope means that all variables declared within a function are always visible within the function body and can be used and reused within the scope of the entire function.
Global variables: variables declared outside the function. Objects that can be accessed anywhere in the code have global scope (all variables without direct assignment of var are global variables)
Local variables: declared inside the function Internal variables and local scopes are generally only accessible within fixed code fragments, most commonly within functions, so in some places you will see people refer to this scope as function scope.
6. Closure
External functions access internal functions and can read internal variables of other functions. In essence, closures are a bridge between the inside of a function and the outside of the function.
7. Prototype chain
Every object has a prototype _proto_, this prototype can also have its own prototype, and so on, forming a prototype chain .
- prototype attribute, the prototype object of the function, is unique to the function, and points to an object from a function.
- __proto__ is the prototype object pointing to the constructor, which is unique to the object.
8. Several ways of inheritance
- Constructor inheritance: In Child, change the Parent’s this pointer to Child’s this Point to, thereby realizing inheritance
Disadvantages: It can only solve the inheritance of attributes, and the values of the attributes are not repeated, but the methods of the parent category cannot be inherited - Prototype chain inheritance: Change the prototype of Child to Parent instance, thereby realizing inheritance
Disadvantages: Because the prototype objects of Child are all New Parent, the properties of the instantiated objects are all the same, and as long as one instance object of the reference type on the Parent is modified, the others will also change. Will be modified accordingly. Because their prototype objects are all shared - Combination method inheritance (combining the first two):
Disadvantages: The prototype object of the parent class is called twice, which is unnecessary, and the student instance The constructor comes from Person - There are also two combined inheritance optimizations
9. How to create functions
Function declaration:
function Fn(){}
Literal/function expression:
var m = function(){}
Constructor:
var sum =new Function(“n1”,”n2”,”return n1+n2”)
10. How to solve asynchronous callback hell
promise, generator, async/await
- promise
let getStuPromise = new Promise((resolve,reject)=>{ getStu(function(res){ resolve(res.data); });});getStuPromise.then((data)=>{ // 得到每个学生的课程 getCourse(); // 还可以继续返回promise 对象})
- generator
function *generatorGetStu(){ let stus = yield getStu(); // 等到getStu异步执行完才会执行getCourse let course = yield getCourse();}
- async/await
The async function is syntactic sugar for the Generator function. Use the keyword async to represent it, and use await inside the function to represent asynchronous
11. Event delegation understanding
通俗的讲,事件就是onclick,onmouseover,onmouseout,等就是事件,委托呢,就是让别人来做,这个事件本来是加在某些元素上的,然而你却加到别人身上来做,完成这个事件.
原理: 利用冒泡的原理,把事件加到父级上,触发执行效果。
target 事件属性可返回事件的目标节点(触发 该事件的节点)
oUl.onmouseover = function(ev){ var ev = ev || window.event; var target = ev.target || ev.srcElement; if(target.nodeeName.toLowerCase() == "li"){ target.style.background = "red"; }}
12.图片的懒加载和预加载
- 预加载:常用的是new Image();,设置其src来实现预载,再使用onload方法回调预载完成事件。
function loadImage(url, callback){ var img = new Image(); //创建一个Image对象,实现图片预下载 img.src = url; if (img.complete){ // 如果图片已经存在于浏览器缓存,直接调用回调函数 callback.call(img); return; // 直接返回,不用再处理onload事件 } img.onload = function (){ //图片下载完毕时异步调用callback函数。 callback.call(img);//将回调函数的this替换为Image对象 ,如果你直接用img.width的时候,图片还没有完全下载下来 };}
懒加载:主要目的是作为服务器前端的优化,缓解服务器前端压力,一次性请求次数减少或延迟请求。
实现方式:
1.第一种是纯粹的延迟加载,使用setTimeOut、setInterval进行加载延迟.
2.第二种是条件加载,符合某些条件,或触发了某些事件才开始异步下载。
3.第三种是可视区加载,即仅加载用户可以看到的区域,这个主要由监控滚动条来实现,一般会在距用户看到某图片前一定距离遍开始加载,这样能保证用户拉下时正好能看到图片。
13.bind,apply,call的区别
都可以改变函数内部this指向
区别:
- callcall传递参数aru1, aru2… 形式
- apply传递参数必须数组形式[arg]
- bind不会调用函数,可以改变函数内部this指向
- 主要应用场景:
1、call经常做继承。
2、apply经常跟数组有关系。比如借助于数学对象实现数组最大值最小值。
3、bind不会调用函数,可以改变函数内部this指向。
14.js的节流和防抖
- 防抖:当持续触发事件时,一定时间段内没有再触发事件,事件处理函数才会执行一次,如果设定时间到来之前,又触发了事件,就重新开始延时。也就是说当一个用户一直触发这个函数,且每次触发函数的间隔小于既定时间,那么防抖的情况下只会执行一次。
- 节流:当持续触发事件时,保证在一定时间内只调用一次事件处理函数,意思就是说,假设一个用户一直触发这个函数,且每次触发小于既定值,函数节流会每隔这个时间调用一次。时间戳和定时器
- 区别:防抖是将多次执行变为最后一次执行,节流是将多次执行变为每隔一段时间执行。
15.前端模块化和组件化
- 模块化:可复用,侧重的功能的封装,主要是针对Javascript代码,隔离、组织复制的javascript代码,将它封装成一个个具有特定功能的的模块。
- 组件化:可复用,更多关注的UI部分,页面的每个部件,比如头部,弹出框甚至确认按钮都可以成为一个组件,每个组件有独立的HTML、css、js代码。
16.js单线程怎么执行异步操作
Js作为浏览器脚本语言,它的主要用途是与用户互动,以及操作DOM。这决定了它只能是单线程,否则会带来很复杂的同步问题。
js怎么异步:浏览器只分配给js一个主线程,用来执行任务(函数),但一次只能执行一个任务,这些任务形成一个任务队列排队等候执行,但前端的某些任务是非常耗时的,比如网络请求,定时器和事件监听,如果让他们和别的任务一样,执行效率会非常的低,甚至导致页面的假死。
所以,浏览器为这些耗时任务开辟了另外的线程,主要包括http请求线程,浏览器定时触发器,浏览器事件触发线程,这些任务是异步的。这些异步任务完成后通过回调函数让主线程知道。
17.手写promise函数
三种状态:pending(过渡)fulfilled(完成)rejected(失败)
function Promise(exector){ let _this = this; //status表示一种状态 let status = “pending”; let value = undefined; let reason = undefined; //成功 function resolve(value){ if(status == “pending”){ _this.value = value; _this.status = “resolve”; } } //执行失败 function reject(value){ if(status == “pending”){ _this.value = value; _this.status = “reject” } } //异步操作 try{ exector(resolve,reject) }catch(e){ reject(e) } //测试then Promise.prototype.then = function(reject,resolve){ let _this = this; if(this.status == “resolve”){ reject(_this.value) } if(this.status == “reject”){ resolve(_this.reason) } }}//new Promise测试let promise = new Promise((reject,resolve)=>{ resolve(“return resolve”);});promise.then(data=>{ console.log(`success${data}`);},err=>{ console.log(`err${data}`);})
18.数组去重
1.遍历并两个对比,splice删除重复的第二个
function unique(arr){ for(var i=0; i<arr.length; i++){ for(var j=i+1; j<arr.length; j++){ if(arr[i]==arr[j]){ //第一个等同于第二个,splice方法删除第二个 arr.splice(j,1); j--; } } }return arr;}
2.indexOf
function unique(arr) { var array = []; for (var i = 0; i < arr.length; i++) { if (array .indexOf(arr[i]) === -1) { array .push(arr[i]) } } return array;}
3.sort
function unique(arr) { arr = arr.sort() var arrry= [arr[0]]; for (var i = 1; i < arr.length; i++) { if (arr[i] !== arr[i-1]) { arrry.push(arr[i]); } } return arrry;}
4.includes (ES6)
function unique(arr) { var array =[]; for(var i = 0; i < arr.length; i++) { if( !array.includes( arr[i]) ) {//includes 检测数组是否有某个值 array.push(arr[i]); } } return array}
19.数组排序
- 冒泡排序:
var arr=[1,5,7,9,16,2,4];//冒泡排序,每一趟找出最大的,总共比较次数为arr.length-1次,每次的比较次数为arr.length-1次,依次递减var temp;for(var i=0;i<arr.length-1;i++){ for(var j=0;j<arr.length-1;j++){ if(arr[j]>arr[j+1]){ temp=arr[j]; arr[j]=arr[j+1]; arr[j+1]=temp; } }}
- 选择排序:(相邻对比)
var arr=[1,23,5,8,11,78,45];var temp;for(var i=0;i<arr.length-1;i++){ for(var j=i+1;j<arr.length;j++){ if(arr[i]>arr[j]){ temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } }}
- sort():
var arr=[1,5,7,9,16,2,4];arr.sort(function(a,b){ return b-a; //降序排列,return a-b; —>升序排列}) //括号里不写回调函数,则默认按照字母逐位升序排列,结果为[1,16,2,4,5,7,9]
20.去除首尾空格
JavaScript 本身并不提供 trim() 方法,不过可以用正则表达式(其中一种)
if(typeof(String.prototype.trim) === "undefined"){ String.prototype.trim = function() { return String(this).replace(/^\s+|\s+$/g, ''); };} if(" dog ".trim() === "dog") { document.write("去除首尾空格成功"); }
21.解决跨域方案
- jsonp:包含回调函数和数据
//1、使用JS动态生成script标签,进行跨域操作function handleResponse(response){ console.log('The responsed data is: '+response.data); //处理获得的Json数据}var script = document.createElement('script');script.src = 'http://www.example.com/data/?callback=handleResponse';document.body.insertBefore(script, document.body.firstChild);//2、手动生成script标签function handleResponse(response){ console.log('The responsed data is: '+response.data); //处理获得的Json数据}<script src="http://www.example.com/data/?callback=handleResponse"></script>//3、使用jQuery进行jsonp操作//jquery会自动生成一个全局函数来替换callback=?中的问号,之后获取到数据后又会自动销毁//$.getJSON方法会自动判断是否跨域,不跨域的话,就调用普通的ajax方法;跨域的话,则会以异步加载js文件的形式来调用jsonp的回调函数。<script> $.getJson('http://www.example.com/data/?callback=?',function(jsondata){ //处理获得的Json数据});</script>
- window.name + iframe
- location.hash+iframe
- window.postMessage(HTML5中的XMLHttpRequest Level 2中的API)
- 通过document.domain+iframe来跨子域(只有在主域相同的时候才能使用该方法)
- 使用跨域资源共享(CORS)来跨域
- 使用Web sockets来跨域
- 使用flash URLLoader来跨域
22.手写ajax
ajax的技术核心是 XMLHttpRequest 对象;
ajax 请求过程:创建 XMLHttpRequest 对象、连接服务器、发送请求、接收响应数据;
(理解)<script type="text/javascript">//通过createXHR()函数创建一个XHR对象:function createXHR() { if (window.XMLHttpRequest) { //IE7+、Firefox、Opera、Chrome 和Safari return new XMLHttpRequest(); } else if (window.ActiveXObject) { //IE6 及以下 var versions = ['MSXML2.XMLHttp','Microsoft.XMLHTTP']; for (var i = 0,len = versions.length; i<len; i++) { try { return new ActiveXObject(version[i]); break; } catch (e) { //跳过 } } } else { throw new Error('浏览器不支持XHR对象!'); }}//封装ajax,参数为一个对象function ajax(obj) { var xhr = createXHR(); //创建XHR对象 //通过使用JS随机字符串解决IE浏览器第二次默认获取缓存的问题 obj.url = obj.url + '?rand=' + Math.random(); obj.data = params(obj.data); //通过params()将名值对转换成字符串 //若是GET请求,则将数据加到url后面 if (obj.method === 'get') { obj.url += obj.url.indexOf('?') == -1 ? '?' + obj.data : '&' + obj.data; } if (obj.async === true) { //true表示异步,false表示同步 //使用异步调用的时候,需要触发readystatechange 事件 xhr.onreadystatechange = function () { if (xhr.readyState == 4) { //判断对象的状态是否交互完成 callback(); //回调 } }; } //在使用XHR对象时,必须先调用open()方法, //它接受三个参数:请求类型(get、post)、请求的URL和表示是否异步。 xhr.open(obj.method, obj.url, obj.async); if (obj.method === 'post') { //post方式需要自己设置http的请求头,来模仿表单提交。 //放在open方法之后,send方法之前。 xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.send(obj.data); //post方式将数据放在send()方法里 } else { xhr.send(null); //get方式则填null } if (obj.async === false) { //同步 callback(); } function callback() { if (xhr.status == 200) { //判断http的交互是否成功,200表示成功 obj.success(xhr.responseText); //回调传递参数 } else { alert('获取数据错误!错误代号:' + xhr.status + ',错误信息:' + xhr.statusText); } }}//名值对转换为字符串function params(data) { var arr = []; for (var i in data) { //特殊字符传参产生的问题可以使用encodeURIComponent()进行编码处理 arr.push(encodeURIComponent(i) + '=' + encodeURIComponent(data[i])); } return arr.join('&');}</script>
实例:
ajax({ method : 'het/post', url : '...', data : { }, success : function (res) { }, error : function(err){ }, async : true});
23.ES6
简述,具体请参考https://blog.csdn.net/Juliet_xmj/article/details/103940173
- 字符串扩展
- 解构表达式
- 函数优化
- 函数参数默认值
- 箭头函数
- 对象的函数属性简写
- 箭头函数结合解构表达式
- map:接收一个函数,将原数组中的所有元素用这个函数处理后放入新数组返回。
- reduce:接收一个函数(必须)和一个初始值(可选),该函数接收两个参数:(上一次reduce处理的结果,数组中要处理的下一个元素)
- promise
const promise = new Promise(function(resolve, reject) { // ... 执行异步操作 if (/* 异步操作成功 */){ resolve(value);// 调用resolve,代表Promise将返回成功的结果 } else { reject(error);// 调用reject,代表Promise会返回失败结果 }});promise.then(function(value){ // 异步执行成功后的回调}).catch(function(error){ // 异步执行失败后的回调 })
- set:本质与数组类似。不同在于Set中只能保存不同元素,如果元素相同会被忽略。
- map:本质是与Object类似的结构。不同在于,Object强制规定key只能是字符串。而 Map结构的key可以是任意对象。
- 模块化:把代码进行拆分,方便重复利用
- 对象扩展
- 数组扩展
24.BOM,DOM
- BOM:指的是浏览器对象模型,它使JavaScript有能力与浏览器进行“对话”
- DOM:是指文档对象模型,通过它,可以范文HTLM文档的所有元素
- window对象:是客户端JavaScript最高层对象之一,由于window对象是其他大部分对象的共同祖先,在调用window对象的方法和属性时,可以省略window对象的应用。
25.jQuery选择器
- 元素选择器:$("p.intro")选取所有 class=“intro” 的
元素。
- 属性选择器:$("[href='#']")选取所有带有 href 值等于 “#” 的元素。
- css选择器:$("p").css("background-color","red");
26.隐式迭代
遍历内部DOM元素(伪数组形式存储)的过程,给匹配到的所有元素进行循环遍历,执行相应的方法,而不需要我们自己进行循环遍历
<ul> <li>web</li> <li>前端</li></ul>//js$("li").html("WEB前端梦之蓝"); //将所有的li标签html内容全部换成“WEB前端梦之蓝”,这个就属于隐式迭代
感谢大家的阅读,希望大家面试成功。
本文转自:https://blog.csdn.net/Juliet_xmj/article/details/106982585
The above is the detailed content of The most comprehensive js and jQuery interview questions in history. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

Detailed explanation of jQuery reference method: Quick start guide jQuery is a popular JavaScript library that is widely used in website development. It simplifies JavaScript programming and provides developers with rich functions and features. This article will introduce jQuery's reference method in detail and provide specific code examples to help readers get started quickly. Introducing jQuery First, we need to introduce the jQuery library into the HTML file. It can be introduced through a CDN link or downloaded

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

How to remove the height attribute of an element with jQuery? In front-end development, we often encounter the need to manipulate the height attributes of elements. Sometimes, we may need to dynamically change the height of an element, and sometimes we need to remove the height attribute of an element. This article will introduce how to use jQuery to remove the height attribute of an element and provide specific code examples. Before using jQuery to operate the height attribute, we first need to understand the height attribute in CSS. The height attribute is used to set the height of an element

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: <

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute
