Front-end JS interview questions
Web Front-end Engineer (Senior)
Web front-end software engineer
Senior Web Front-end Development Engineer (VUE
Get into the business
1. Enter a value and return its data type **
function type(para) {
return Object.prototype.toString.call(para)
}
Copy the code
2. Array deduplication
function unique1(arr) {
return [...new Set(arr)]
}
function unique2(arr) {
var obj = {};
return arr.filter(ele= > {
if(! obj[ele]) { obj[ele] =true;
return true; }})}function unique3(arr) {
var result = [];
arr.forEach(ele= > {
if (result.indexOf(ele) == -1) {
result.push(ele)
}
})
return result;
}
Copy the code
3. Deduplication of the string
String.prototype.unique = function () {
var obj = {},
str = ' ',
len = this.length;
for (var i = 0; i < len; i++) {
if(! obj[this[i]]) {
str += this[i];
obj[this[i]] = true; }}return str;
}
Copy the code
// Remove consecutive strings
function uniq(str) {
return str.replace(/(\w)\1+/g.'$1')}Copy the code
4. Deep copy shallow copy
// deep clone (deep clone does not consider functions)
function deepClone(obj, result) {
var result = result || {};
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
if (typeof obj[prop] == 'object'&& obj[prop] ! = =null) {
// Reference value (obj/array) and not null
if (Object.prototype.toString.call(obj[prop]) == '[object Object]') {
/ / object
result[prop] = {};
} else {
/ / array
result[prop] = [];
}
deepClone(obj[prop], result[prop])
} else {
// The original value or func
result[prop] = obj[prop]
}
}
}
return result;
}
// Depth clone is for reference values
function deepClone(target) {
if (typeof(target) ! = ='object') {
return target;
}
var result;
if (Object.prototype.toString.call(target) == '[object Array]') {
/ / array
result = []
} else {
/ / object
result = {};
}
for (var prop in target) {
if (target.hasOwnProperty(prop)) {
result[prop] = deepClone(target[prop])
}
}
return result;
}
// The function cannot be copied
var o1 = jsON.parse(jsON.stringify(obj1));
Copy the code
5. Reverse underlying principle and extension
// Change the original array
Array.prototype.myReverse = function () {
var len = this.length;
for (var i = 0; i < len; i++) {
var temp = this[i];
this[i] = this[len - 1 - i];
this[len - 1 - i] = temp;
}
return this;
}
Copy the code
6. Inheritance of the Holy Grail mode
function inherit(Target, Origin) {
function F() {};
F.prototype = Origin.prototype;
Target.prototype = new F();
Target.prototype.constructor = Target;
// Final prototype pointing
Target.prop.uber = Origin.prototype;
}
Copy the code
7. Find the first occurrence of a letter in a string
String.prototype.firstAppear = function () {
var obj = {},
len = this.length;
for (var i = 0; i < len; i++) {
if (obj[this[i]]) {
obj[this[i]]++;
} else {
obj[this[i]] = 1; }}for (var prop in obj) {
if (obj[prop] == 1) {
returnprop; }}}Copy the code
Find the NTH parent of the element
function parents(ele, n) {
while (ele && n) {
ele = ele.parentElement ? ele.parentElement : ele.parentNode;
n--;
}
return ele;
}
Copy the code
Returns the NTH sibling of the element
function retSibling(e, n) {
while (e && n) {
if (n > 0) {
if (e.nextElementSibling) {
e = e.nextElementSibling;
} else {
for(e = e.nextSibling; e && e.nodeType ! = =1; e = e.nextSibling);
}
n--;
} else {
if (e.previousElementSibling) {
e = e.previousElementSibling;
} else {
for(e = e.previousElementSibling; e && e.nodeType ! = =1; e = e.previousElementSibling); } n++; }}return e;
}
Copy the code
10. Package MyChildren to solve browser compatibility problems
function myChildren(e) {
var children = e.childNodes,
arr = [],
len = children.length;
for (var i = 0; i < len; i++) {
if (children[i].nodeType === 1) {
arr.push(children[i])
}
}
return arr;
}
Copy the code
11. Determine if the element has children
function hasChildren(e) {
var children = e.childNodes,
len = children.length;
for (var i = 0; i < len; i++) {
if (children[i].nodeType === 1) {
return true; }}return false;
}
Copy the code
12. I insert one element after another
Element.prototype.insertAfter = function (target, elen) {
var nextElen = elen.nextElenmentSibling;
if (nextElen == null) {
this.appendChild(target);
} else {
this.insertBefore(target, nextElen); }}Copy the code
13, return the current time (year month day hour minute second)
function getDateTime() {
var date = new Date(),
year = date.getFullYear(),
month = date.getMonth() + 1,
day = date.getDate(),
hour = date.getHours() + 1,
minute = date.getMinutes(),
second = date.getSeconds();
month = checkTime(month);
day = checkTime(day);
hour = checkTime(hour);
minute = checkTime(minute);
second = checkTime(second);
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
return "" + year + "Year" + month + "Month" + day + "Day" + hour + "When" + minute + "Points" + second + "Seconds"
}
Copy the code
14. Get the scrolling distance of the scroll bar
function getScrollOffset() {
if (window.pageXOffset) {
return {
x: window.pageXOffset,
y: window.pageYOffset
}
} else {
return {
x: document.body.scrollLeft + document.documentElement.scrollLeft,
y: document.body.scrollTop + document.documentElement.scrollTop
}
}
}
Copy the code
15. Get the size of the viewport
function getViewportOffset() {
if (window.innerWidth) {
return {
w: window.innerWidth,
h: window.innerHeight
}
} else {
// Ie8 and below
if (document.compatMode === "BackCompat") {
// Weird mode
return {
w: document.body.clientWidth,
h: document.body.clientHeight
}
} else {
// Standard mode
return {
w: document.documentElement.clientWidth,
h: document.documentElement.clientHeight
}
}
}
}
Copy the code
Get any attributes of any element
function getStyle(elem, prop) {
return window.getComputedStyle ? window.getComputedStyle(elem, null)[prop] : elem.currentStyle[prop]
}
Copy the code
Compatible code for binding events
function addEvent(elem, type, handle) {
if (elem.addEventListener) { // Non-IE and non-IE9
elem.addEventListener(type, handle, false);
} else if (elem.attachEvent) { / / ie6 ie8
elem.attachEvent('on' + type, function () { handle.call(elem); })}else {
elem['on'+ type] = handle; }}Copy the code
18. Untying events
function removeEvent(elem, type, handle) {
if (elem.removeEventListener) { // Non-IE and non-IE9
elem.removeEventListener(type, handle, false);
} else if (elem.detachEvent) { / / ie6 ie8
elem.detachEvent('on' + type, handle);
} else {
elem['on' + type] = null; }}Copy the code
19. Cancel bubbling compatibility code
function stopBubble(e) {
if (e && e.stopPropagation) {
e.stopPropagation();
} else {
window.event.cancelBubble = true; }}Copy the code
Check if the string is palindrome
function isPalina(str) {
if (Object.prototype.toString.call(str) ! = ='[object String]') {
return false;
}
var len = str.length;
for (var i = 0; i < len / 2; i++) {
if(str[i] ! = str[len -1 - i]) {
return false; }}return true;
}
Copy the code
21. Check if the string is palindrome
function isPalindrome(str) {
str = str.replace(/\W/g.' ').toLowerCase();
console.log(str)
return (str == str.split(' ').reverse().join(' '))}Copy the code
22, compatible with getElementsByClassName method
Element.prototype.getElementsByClassName = Document.prototype.getElementsByClassName = function (_className) {
var allDomArray = document.getElementsByTagName(The '*');
var lastDomArray = [];
function trimSpace(strClass) {
var reg = /\s+/g;
return strClass.replace(reg, ' ').trim()
}
for (var i = 0; i < allDomArray.length; i++) {
var classArray = trimSpace(allDomArray[i].className).split(' ');
for (var j = 0; j < classArray.length; j++) {
if (classArray[j] == _className) {
lastDomArray.push(allDomArray[i]);
break; }}}return lastDomArray;
}
Copy the code
23. Motion function
function animate(obj, json, callback) {
clearInterval(obj.timer);
var speed,
current;
obj.timer = setInterval(function () {
var lock = true;
for (var prop in json) {
if (prop == 'opacity') {
current = parseFloat(window.getComputedStyle(obj, null)[prop]) * 100;
} else {
current = parseInt(window.getComputedStyle(obj, null)[prop]);
}
speed = (json[prop] - current) / 7;
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
if (prop == 'opacity') {
obj.style[prop] = (current + speed) / 100;
} else {
obj.style[prop] = current + speed + 'px';
}
if(current ! = json[prop]) { lock =false; }}if (lock) {
clearInterval(obj.timer);
typeof callback == 'function' ? callback() : ' '; }},30)}Copy the code
24. Elastic exercise
function ElasticMovement(obj, target) {
clearInterval(obj.timer);
var iSpeed = 40,
a, u = 0.8;
obj.timer = setInterval(function () {
a = (target - obj.offsetLeft) / 8;
iSpeed = iSpeed + a;
iSpeed = iSpeed * u;
if (Math.abs(iSpeed) <= 1 && Math.abs(a) <= 1) {
console.log('over')
clearInterval(obj.timer);
obj.style.left = target + 'px';
} else {
obj.style.left = obj.offsetLeft + iSpeed + 'px'; }},30);
}
Copy the code
25. Encapsulate your own forEach methods
Array.prototype.myForEach = function (func, obj) {
var len = this.length;
var _this = arguments[1]?arguments[1] : window;
// var _this=arguments[1]||window;
for (var i = 0; i < len; i++) {
func.call(_this, this[i], i, this)}}Copy the code
26. Encapsulate your own filter method
Array.prototype.myFilter = function (func, obj) {
var len = this.length;
var arr = [];
var _this = arguments[1] | |window;
for (var i = 0; i < len; i++) {
func.call(_this, this[i], i, this) && arr.push(this[i]);
}
return arr;
}
Copy the code
27, Array map method
Array.prototype.myMap = function (func) {
var arr = [];
var len = this.length;
var _this = arguments[1] | |window;
for (var i = 0; i < len; i++) {
arr.push(func.call(_this, this[i], i, this));
}
return arr;
}
Copy the code
Array every method
Array.prototype.myEvery = function (func) {
var flag = true;
var len = this.length;
var _this = arguments[1] | |window;
for (var i = 0; i < len; i++) {
if (func.apply(_this, [this[i], i, this= =])false) {
flag = false;
break; }}return flag;
}
Copy the code
29, Array reduce method
Array.prototype.myReduce = function (func, initialValue) {
var len = this.length,
nextValue,
i;
if(! initialValue) {// No second argument is passed
nextValue = this[0];
i = 1;
} else {
// The second argument is passed
nextValue = initialValue;
i = 0;
}
for (; i < len; i++) {
nextValue = func(nextValue, this[i], i, this);
}
return nextValue;
}
Copy the code
30. Get parameters from the URL
function getWindonHref() {
var sHref = window.location.href;
var args = sHref.split('? ');
if (args[0] === sHref) {
return ' ';
}
var hrefarr = args[1].split(The '#') [0].split('&');
var obj = {};
for (var i = 0; i < hrefarr.length; i++) {
hrefarr[i] = hrefarr[i].split('=');
obj[hrefarr[i][0]] = hrefarr[i][1];
}
return obj;
}
Copy the code
31, Array sort
[left] + min + [right]
function quickArr(arr) {
if (arr.length <= 1) {
return arr;
}
var left = [],
right = [];
var pIndex = Math.floor(arr.length / 2);
var p = arr.splice(pIndex, 1) [0];
for (var i = 0; i < arr.length; i++) {
if (arr[i] <= p) {
left.push(arr[i]);
} else{ right.push(arr[i]); }}/ / recursion
return quickArr(left).concat([p], quickArr(right));
}
/ / the bubbling
function bubbleSort(arr) {
for (var i = 0; i < arr.length - 1; i++) {
for (var j = i + 1; j < arr.length; j++) {
if (arr[i] > arr[j]) {
vartemp = arr[i]; arr[i] = arr[j]; arr[j] = temp; }}}return arr;
}
function bubbleSort(arr) {
var len = arr.length;
for (var i = 0; i < len - 1; i++) {
for (var j = 0; j < len - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
var temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp; }}}return arr;
}
Copy the code
Traverse the Dom tree
// Given a DOM element on a page, access the element itself and all its descendants (not just its immediate children).
// For each element accessed, the function passes the element to the provided callback function
function traverse(element, callback) {
callback(element);
var list = element.children;
for (var i = 0; i < list.length; i++) { traverse(list[i], callback); }}Copy the code
Native JS encapsulates Ajax
function ajax(method, url, callback, data, flag) {
var xhr;
flag = flag || true;
method = method.toUpperCase();
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject('Microsoft.XMLHttp');
}
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(2) callback(xhr.responseText); }}if (method == 'GET') {
var date = new Date(),
timer = date.getTime();
xhr.open('GET', url + '? ' + data + '&timer' + timer, flag);
xhr.send()
} else if (method == 'POST') {
xhr.open('POST', url, flag);
xhr.setRequestHeader('Content-Type'.'application/x-www-form-urlencoded'); xhr.send(data); }}Copy the code
Load script asynchronously
function loadScript(url, callback) {
var oscript = document.createElement('script');
if (oscript.readyState) { // Internet Explorer 8 or later
oscript.onreadystatechange = function () {
if (oscript.readyState === 'complete' || oscript.readyState === 'loaded') { callback(); }}}else {
oscript.onload = function () {
callback()
};
}
oscript.src = url;
document.body.appendChild(oscript);
}
Copy the code
Cookie management
var cookie = {
set: function (name, value, time) {
document.cookie = name + '=' + value + '; max-age=' + time;
return this;
},
remove: function (name) {
return this.setCookie(name, ' ', -1);
},
get: function (name, callback) {
var allCookieArr = document.cookie.split('; ');
for (var i = 0; i < allCookieArr.length; i++) {
var itemCookieArr = allCookieArr[i].split('=');
if (itemCookieArr[0] === name) {
return itemCookieArr[1]}}return undefined; }}Copy the code
Implement bind()
Function.prototype.myBind = function (target) {
var target = target || window;
var _args1 = [].slice.call(arguments.1);
var self = this;
var temp = function () {};
var F = function () {
var _args2 = [].slice.call(arguments.0);
var parasArr = _args1.concat(_args2);
return self.apply(this instanceof temp ? this : target, parasArr)
}
temp.prototype = self.prototype;
F.prototype = new temp();
return F;
}
Copy the code
Implement the call() method
Function.prototype.myCall = function () {
var ctx = arguments[0] | |window;
ctx.fn = this;
var args = [];
for (var i = 1; i < arguments.length; i++) {
args.push(arguments[i])
}
varresult = ctx.fn(... args);delete ctx.fn;
return result;
}
Copy the code
Implement the apply() method
Function.prototype.myApply = function () {
var ctx = arguments[0] | |window;
ctx.fn = this;
if (!arguments[1]) {
var result = ctx.fn();
delete ctx.fn;
return result;
}
varresult = ctx.fn(... arguments[1]);
delete ctx.fn;
return result;
}
Copy the code
39, stabilization,
function debounce(handle, delay) {
var timer = null;
return function () {
var _self = this,
_args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
handle.apply(_self, _args)
}, delay)
}
}
Copy the code
40, throttling
function throttle(handler, wait) {
var lastTime = 0;
return function (e) {
var nowTime = new Date().getTime();
if (nowTime - lastTime > wait) {
handler.apply(this.arguments); lastTime = nowTime; }}}Copy the code
RequestAnimFrame compatibility method
window.requestAnimFrame = (function () {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function (callback) {
window.setTimeout(callback, 1000 / 60); }; }) ();Copy the code
CancelAnimFrame compatibility method
window.cancelAnimFrame = (function () {
return window.cancelAnimationFrame ||
window.webkitCancelAnimationFrame ||
window.mozCancelAnimationFrame ||
function (id) {
window.clearTimeout(id); }; }) ();Copy the code
43, JSONP underlying methods
function jsonp(url, callback) {
var oscript = document.createElement('script');
if (oscript.readyState) { // Internet Explorer 8 or later
oscript.onreadystatechange = function () {
if (oscript.readyState === 'complete' || oscript.readyState === 'loaded') { callback(); }}}else {
oscript.onload = function () {
callback()
};
}
oscript.src = url;
document.body.appendChild(oscript);
}
Copy the code
44, Get url parameters
function getUrlParam(sUrl, sKey) {
var result = {};
sUrl.replace(/(\w+)=(\w+)(? =[&|#])/g.function (ele, key, val) {
if(! result[key]) { result[key] = val; }else {
vartemp = result[key]; result[key] = [].concat(temp, val); }})if(! sKey) {return result;
} else {
return result[sKey] || ' '; }}Copy the code
Formatting time
function formatDate(t, str) {
var obj = {
yyyy: t.getFullYear(),
yy: ("" + t.getFullYear()).slice(-2),
M: t.getMonth() + 1.MM: ("0" + (t.getMonth() + 1)).slice(-2),
d: t.getDate(),
dd: ("0" + t.getDate()).slice(-2),
H: t.getHours(),
HH: ("0" + t.getHours()).slice(-2),
h: t.getHours() % 12.hh: ("0" + t.getHours() % 12).slice(-2),
m: t.getMinutes(),
mm: ("0" + t.getMinutes()).slice(-2),
s: t.getSeconds(),
ss: ("0" + t.getSeconds()).slice(-2),
w: ['day'.'一'.'二'.'三'.'four'.'five'.'六'][t.getDay()]
};
return str.replace(/([a-z]+)/ig.function ($1) {
return obj[$1]}); }Copy the code
46. Verify the mailbox regular expression
function isAvailableEmail(sEmail) {
var reg = /^([\w+\.])+@\w+([.]\w+)+$/
return reg.test(sEmail)
}
Copy the code
47. The function Corrification
// is a technique for converting a function that takes multiple arguments into a function that takes a single argument (the first argument of the original function) and returns a new function that takes the remaining arguments and returns the result
function curryIt(fn) {
var length = fn.length,
args = [];
var result = function (arg) {
args.push(arg);
length--;
if (length <= 0) {
return fn.apply(this, args);
} else {
returnresult; }}return result;
}
Copy the code
Add large numbers
function sumBigNumber(a, b) {
var res = ' './ / the result
temp = 0; // The result of the bitwise addition and carry
a = a.split(' ');
b = b.split(' ');
while (a.length || b.length || temp) {
2.~~undefined==0
temp += ~~a.pop() + ~~b.pop();
res = (temp % 10) + res;
temp = temp > 9;
}
return res.replace(/ ^ 0 + /.' ');
}
Copy the code
49. Singleton mode
function getSingle(func) {
var result;
return function () {
if(! result) { result =new func(arguments);
}
returnresult; }}Copy the code