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;
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 .
8. Several ways of inheritance
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
let getStuPromise = new Promise((resolve,reject)=>{ getStu(function(res){ resolve(res.data); });});getStuPromise.then((data)=>{ // 得到每个学生的课程 getCourse(); // 还可以继续返回promise 对象})
function *generatorGetStu(){ let stus = yield getStu(); // 等到getStu异步执行完才会执行getCourse let course = yield getCourse();}
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.图片的懒加载和预加载
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指向
区别:
14.js的节流和防抖
15.前端模块化和组件化
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; } }}
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.解决跨域方案
//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>
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
const promise = new Promise(function(resolve, reject) { // ... 执行异步操作 if (/* 异步操作成功 */){ resolve(value);// 调用resolve,代表Promise将返回成功的结果 } else { reject(error);// 调用reject,代表Promise会返回失败结果 }});promise.then(function(value){ // 异步执行成功后的回调}).catch(function(error){ // 异步执行失败后的回调 })
24.BOM,DOM
25.jQuery选择器
元素。
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!