Home>Article>Web Front-end> The most comprehensive js and jQuery interview questions in history

The most comprehensive js and jQuery interview questions in history

烟雨青岚
烟雨青岚 forward
2020-07-10 11:23:07 7201browse

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
      

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;iarr[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;iarr[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数据}//3、使用jQuery进行jsonp操作//jquery会自动生成一个全局函数来替换callback=?中的问号,之后获取到数据后又会自动销毁//$.getJSON方法会自动判断是否跨域,不跨域的话,就调用普通的ajax方法;跨域的话,则会以异步加载js文件的形式来调用jsonp的回调函数。
  • 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 对象、连接服务器、发送请求、接收响应数据;

(理解)

实例:

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” 的e388a4556c0f65e1904146cc1a846bee元素。
  • 属性选择器:$("[href='//m.sbmmt.com/m/faq/#']")选取所有带有 href 值等于 “#” 的元素。
  • css选择器:$("p").css("background-color","red");

26.隐式迭代

遍历内部DOM元素(伪数组形式存储)的过程,给匹配到的所有元素进行循环遍历,执行相应的方法,而不需要我们自己进行循环遍历

  • web
  • 前端
//js$("li").html("WEB前端梦之蓝"); //将所有的li标签html内容全部换成“WEB前端梦之蓝”,这个就属于隐式迭代

感谢大家的阅读,希望大家面试成功。

本文转自:https://blog.csdn.net/Juliet_xmj/article/details/106982585

推荐教程:《JS教程》,《jQuery教程

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!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete