One, foreword

Everybody is good! I am your happy little sister, wish you in reading this article to absorb knowledge at the same time is happy and cheerful ☺️

Recently also saw a lot of nuggets article, the use of these resources combined with their usual code summary, comb became today’s article. Here are some interview questions and some code snippets that are often used in work. I hope they will help you on the screen 😉

At the same time, the code of this article has also made a detailed note, convenient for everyone to read and understand, if there is still not understand can be discussed in the comment area.

Let’s start our tour in the code world ~~~

Second, the code

1. Processing the URL

Implementation effect: will the URL in the address bar of the question mark at the back of the content into the object’s form: http://www.baidu.com/search?name=li&age=18#student = > {HASH: “student”, the name: “li”, the age: “18”}

1.1 Using methods in arrays

let str = 'http://www.baidu.com/search?name=li&age=18#student';
function urlQuery(str) {
    / / get? And # index
    let askIndex = str.indexOf('? '),
        polIndex = str.indexOf(The '#'),
 askText = ' '. polText = ' ';  // Store the final result we want  let obj = {};  / / #? The rest goes to polText and askText polIndex ! =- 1 ? polText = str.substring(polIndex + 1) : null; askIndex ! =- 1 ? askText = str.substring(askIndex + 1, polIndex) : null;  // Store it in an object  polText ? obj['HASH'] = polText : null;  if (askText) {  askText.split('&').forEach((item, index) = > {  item = item.split('=');  obj[item[0]]=item[1];  });  }  return obj; } console.log(urlQuery(str)); //=> {HASH: "student", name: "li", age: "18"}  Copy the code

1.2 Implementation of re

If you are not familiar with the regex in the following example, check out this regex section: Regex Learning

let str = 'http://www.baidu.com/search?name=li&age=18#student';
function urlQuery(str) {
    let obj = {};
    // Regular matches = both sides
    str.replace(/([^=?&#]+)=([^=?&#]+)/g,(_,group1,group2)=>{
 obj[group1]=group2;  });  // Match the string after #  str.replace(/#([^=?&#]+)/g,(_,group1)=>{  obj['HASH']=group1;  });  return obj; } console.log(urlQuery(str)); //=> {name: "li", age: "18", HASH: "student"} Copy the code

2. Array deduplication

Implementation effect: the array of duplicates removed. For example: [1,2,3,4,2,1] => [1,2,3,4]

2.1 Implementation of O(n^2) time complexity

let ary = [1.2.2.3.4.2.1.3.1.3];
function unique(ary) {
    // The double for loop compares the current item with each subsequent item
    for (let i = 0; i < ary.length; i++) {
        let item = ary[i];
 for (let j = i + 1; j < ary.length; j++) {  if (item == ary[j]) {  // If the current term is equal to the following term, then the last term is assigned to the following term and its length is reduced by one,  ary[j] = ary[ary.length - 1];  ary.length--;  j--;  }  }  }  return ary; } console.log(unique(ary)); Copy the code

2.2 Implementation of O(n) time complexity

let ary = [1.2.2.3.4.2.1.3.1.3];
function unique(ary) {
    let obj = {};
    for (let i = 0; i < ary.length; i++) {
        let item = ary[i];
 if(obj[item] ! = =undefined) {  ary[i] = ary[ary.length - 1];  ary.length--;  // Resolve array collapse  i--;  }  obj[item] = item;  }  return ary; } console.log(unique(ary)); Copy the code

2.3 Use ES6 Set implementation

Set is a data structure with no duplicates in ES6

let ary = [1.2.2.3.4.2.1.3.1.3];
ary = Array.from(new Set(ary));
console.log(ary);
Copy the code

3. Built-in implementation of new

function Fn(x,y){
    this.x=x;
    this.y=y;
}
function _new(func){
 let params=Array.from(arguments).slice(1);  let obj=Object.create(func.prototype);  let result=func.apply(obj,params);  // If there is a return in the class and it is an imported data type, return from the class  if(result! = =null&& (typeof result==='object'||typeof result==='function')) { return result;  }  return obj; } let f1=_new(Fn,10.20); Copy the code

4. When to print ‘OK’

vara = ? ;if (a == 1 && a == 2 && a == 3) {
    console.log('ok');
}
Copy the code
/ / a
var a = {
  n:0.  toString:function(){
    return ++this.n;
 } }  / / 2 var a = [1.2.3]; a.toString = a.shift;  3 / / solution var i = 0; Object.defineProperty(window.'a', { get() { // The get method must be triggered if the value of a is obtained  return ++i;  } }) Copy the code

5. The built-in call

Function.prototype.changeThis = function changeThis(context,... args){
  if(context == null) {    //== : null and undefined are equal, because if is passed as undefined or null
    context = window;
  }
 if(typeofcontext ! = ='object' && typeofcontext ! = ='function') { context = new context.constructor(context);  }  let uniqueKey = ` $The ${new Date().getTime()}`;  context[uniqueKey] = this;  letresult = context[uniqueKey](... args); delete context[uniqueKey];  return result; } Copy the code

6. The built-in apply

Function.prototype.myApply = function (context) {
    Context points to window if no object is passed or if the value passed is empty
    if (context == null) {
        context = window
    }
 let fn = mySymbol(context)  context[fn] = this // Add a method to the context pointing to this  // The first parameter, this, is passed to the other fn functions  let arg = [...arguments].slice(1) //[... XXX] returns a new array by searching slice  context[fn](arg) / / execution fn  delete context[fn] // Delete method }  Copy the code

7. The built-in bind

Function.prototype.bind = function (context) {
    // Returns a function that binds this, where we need to save this
    let self = this
    // Can support currie transfer parameters, save parameters
    let arg = [...arguments].slice(1)
 // Return a function  return function () {  // We need to get the storage parameters again because we support currified form parameter passing  let newArg = [...arguments]  console.log(newArg)  // Return the function binding this, passing in the twice-saved argument  // Consider that the return function has a return value that does return  return self.apply(context, arg.concat(newArg))  } }  Copy the code

8. If

Debounce: Instead of executing a function as soon as an event is triggered, it is executed once at a specified time interval to reduce the number of times the function is executed. (Can only be executed once at a time.)

/ * * @Parma
* func Specifies the function to be executed* wait Interval Indicates the time to wait* Immediate triggers execution at start or end boundary (true at start boundary) * @return * The function that can be called* By don't be emotional on 2020/05/24* / function debounce(func, wait, immediate) {  let result = null. timeout = null;  return function (. args) {  let context = this.now = immediate && ! timeout; clearTimeout(timeout); // Important: Before setting a new timer, clear all the previous timers, because the purpose of anti-shaking is to wait for the time, execute only once  timeout = setTimeout((a)= > {  if(! immediate) result = func.call(context, ... args); clearTimeout(timeout);  timeout = null;  }, wait);  if(now) result = func.call(context, ... args); } } Copy the code

9. The throttle

Function throttling: To reduce the frequency of execution, but to perform multiple executions at a given time, rather than once, as with stabilization

/ ** throttle: Functions are throttled to reduce the frequency of execution and are executed once a certain interval has been reached *   @params
* func: functions that need to be executed* wait: Set the interval * @return * Returns the function that can be called* By not feeling on 2019/08/20* / let throttle = function (func, wait) {  let timeout = null. result = null. previous = 0; //=> Last execution time  return function (. args) {  let now = new Date. context = this;  //=> Remaining Is less than or equal to 0. It indicates that the interval of remaining exceeds one interval  let remaining = wait - (now - previous);  if (remaining <= 0) {  clearTimeout(timeout);  previous = now;  timeout = null;  result = func.apply(context, args);  } else if(! timeout) { timeout = setTimeout((a)= > {  previous = new Date;  timeout = null;  result = func.apply(context, args);  }, remaining);  }  return result;  }; };  Copy the code

10. Deep cloning

Not only do we clone the first level to the new array, but if there are multiple levels in the original array, we clone each level and assign values to each level of the new array

function cloneDeep(obj) {
  // If the Symbol is not an object, it returns the original value.
  if (obj === null) return null;
  if (typeofobj ! = ="object") return obj;

 // Filter out special objects (regular objects or date objects) : create a new instance of the current class using the original value, so that the cloned instance is the new one, but with the same value as before  if (obj instanceof RegExp) return new RegExp(obj);  if (obj instanceof Date) return new Date(obj);   // If we pass an array or object, we need to create a new array or object to store the original data  // obj.constructor gets the current value (Array/Object)  let cloneObj = new obj.constructor;  for (let key in obj) {  // Loop over each item in the original data, assigning each item to the new object  if(! obj.hasOwnProperty(key))break;  cloneObj[key] = cloneDeep(obj[key]);  }  return cloneObj; }  Copy the code
image

11. A deep comparison

function _assignDeep(obj1, obj2) {
  // Assign a deep clone of each item in OBJ1 to the new object
  let obj = _cloneDeep(obj1);

  // Replace each item in OBJ with OBJ2
 for (let key in obj2) {  if(! obj2.hasOwnProperty(key))break;  let v2 = obj2[key],  v1 = obj[key];  // If OBJ2 is traversed by an object and OBJ is also an object, it cannot be replaced directly, and the two objects need to be merged again, and the latest result of the merger is assigned to the item in the new object  if (typeof v1 === "object" && typeof v2 === "object") {  obj[key] = _assignDeep(v1, v2);  continue;  }  obj[key] = v2;  }   return obj; } Copy the code

12. Verify your phone number

Rule: the first of the 11 digits is the number 1 and the second is any of the numbers 3-9

let reg = /^1[3-9]\d{9}$/;
console.log(reg.test('13245678945')); //true
console.log(reg.test('1324567895'));  //false
console.log(reg.test('12245678945'));  //false
Copy the code

13. Verify whether it is a valid number

Rule: can start with a + – integer bit: can be any number from 0 to 9 if it is a digit; If it’s a multi-digit number, it can’t start with a 0; Decimal place: If there is a decimal place, there is at least one digit after it, or there may be no decimal place

let reg = / ^ (+ -)? (\d|[1-9]\d+)(\.\d+)? $/;
console.log(reg.test('0.2')); //true
console.log(reg.test('02.1'));  //false
console.log(reg.test('20.));  //false
Copy the code

14. Verify the password

Rule: 6-16 digits must be alphanumeric

let reg = / ^ (? =.*\d)(? =.*[a-z])(? =. * [a-z]) [\ d (a-z) (a-z)] 6 16th} {$/;
Copy the code

15. Verify real names

Rule: The name must be Chinese characters with a length of 2-10 characters

let reg = / ^ [\ u4E00 - \ u9FA5] {2, 10} (· [\ u4E00 - \ u9FA5] {2, 10})? $/;
Copy the code

16. Verify email

Rule: The email name consists of ‘alphanumeric underscores -.’ but -/. Can continuous appear nor as beginning \ w + ((\ w +) | (. \ w +)); @ can be followed by alphanumeric, can appear multiple @[A-zA-Z0-9]+; Additions to @ names: multi-domain com.cn; Corporate domain (. | -) [A Za – z0-9] +). Com /. Cn domain names such as. [A Za – z0-9] +

let reg = /^\w+((-\w+)|(\.\w+))*@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/

Copy the code

17. Verify your ID number

let reg =/^([1-9]\d{5})((19|20)\d{2})(0[1-9]|10|11|12)(0[1-9]|[1-2]\d|30|31)\d{3}(\d|x)$/i;
Copy the code

18. Time format string

If the month and day are less than ten, replace them with the year, month and day format

let time = '2020-5-27';
String.prototype.formatTime = function formatTime(template) {
    let arr = this.match(/\d+/g).map(item= > {
        return item.length < 2 ? '0' + item : item;
    });
 template = template || '{0} year {1} Month {2} day {3} {4} minutes {5} seconds';  return template.replace(/\{(\d+)\}/g, (_, group) => {  return arr[group] || "00";  }); }; console.log(time.formatTime()); //=> 2020 May 27, 00 hours, 00 minutes, 00 seconds Copy the code

19. The character that occurs the most times in a string and the number of occurrences

let str = "hello";
let ary = [...new Set(str.split(' '))];
let max = 0;
let code = ' '; for (let i = 0; i < ary.length; i++) {
    // Create a regular match character
 let reg = new RegExp(ary[i], 'g');  // Use match to find out where the corresponding character appears in the string, and take the length of the array returned by match, i.e. the number of occurrences of the corresponding string  let val = str.match(reg).length; // Update the most frequently occurring character and number  if (val > max) {  max = val;  code = ary[i];  } else if (val === max) {  // Handle the same number of different characters  code = `${code},${ary[i]}`;  } } console.log(The characters that appear most frequently are:${code}, The Times are:${max}`); //=> The character that occurs most frequently is l, and the number of times is 2  Copy the code

The micrometer

String.prototype.millimeter = function millimeter() {
    return this.replace(/ \ d {1, 3} (? =(\d{3})+$)/g, value => {
        return value + ', ';
    });
};
let str = "2312345638"; str = str.millimeter(); console.log(str); / / = > "2312345638" Copy the code

21. Inheritance (I) Prototype inheritance

function Parent() {
    this.x = 100;
}
Parent.prototype.getX = function getX() {
    return this.x;
};  function Child() {  this.y = 200; } Child.prototype = new Parent; //=> Prototype inheritance Child.prototype.getY = function getY() {  return this.y; }; let c1 = new Child; console.log(c1); Copy the code

We should call it a day

function Parent() {
    this.x = 100;
}
Parent.prototype.getX = function getX() {
    return this.x;
}; function Child() {  // In the subclass constructor, the parent class is executed as a normal method (there is no instance of the parent class, so the stuff on the parent class prototype is not relevant)  // this -> Child instance c1  Parent.call(this); // this. X =100; // this. X =100; // this.  this.y = 200; } Child.prototype.getY = function getY() {  return this.y; }; let c1 = new Child; console.log(c1);  Copy the code

23. Inheritance (iii) Combinatorial inheritance

function Parent() {
    this.x = 100;
}
Parent.prototype.getX = function getX() {
    return this.x;
}; function Child() {  Parent.call(this);//call  this.y = 200; } Child.prototype = Object.create(Parent.prototype);// Prototype inheritance Child.prototype.constructor = Child; Child.prototype.getY = function getY() {  return this.y; };  let c1 = new Child; console.log(c1);  Copy the code

24. Array flattening

[1, 2, [3], [4, 5, [6, [7, 8, 9]]]] = > [1,2,3,4,5,6,7,8,9,]

var arr = [1.2[3], [4.5[6[7.8.9]]]];
function flatten(arr) {
    return arr.reduce((res, next) = > {
        return res.concat(Array.isArray(next) ? flatten(next) : next);
} []);} console.log(flatten(arr)); Copy the code

25. Modify the code to output 0-9

Closure solutions

for (var i = 0; i< 10; i++){
 setTimeout((a)= > {
  console.log(i);
    }, 1000)
}
Copy the code
for (let i = 0; i< 10; i++){
 setTimeout((a)= > {
  console.log(i);
    }, 1000)
}
Copy the code

26. Bubble sort

var ary = [3.1.5.2];
function bubble(ary) {
    // The last round is the smallest
    for (var i = 0; i < ary.length - 1; i++) {
        // Compare pairs
 for (var j = 0; j < ary.length - 1 - i; j++) {  if (ary[j] > ary[j + 1]) {  // Destruct the assignment  [ary[j], ary[j + 1]] = [ary[j + 1], ary[j]]  }  }  }  return ary; } var res = bubble(ary); console.log(res); Copy the code

27. Quicksort

function quickSort(ary){
    if(ary.length<1) {        return ary;
    }
   var centerIndex=Math.floor(ary.length/2);
 // Remove the middle item from the array  var centerValue=ary.splice(centerIndex,1) [0];  // Create two new arrays: leftAry,rightAry; Compare the remaining items in ary with the middle items. If the large items are placed in the right array, the small items are placed in the left array.  var leftAry=[],rightAry=[];  for(var i=0; i<ary.length; i++){ if(ary[i]<centerValue){  leftAry.push(ary[i]);  }else{  rightAry.push(ary[i]);  }  }  return quickSort(leftAry).concat(centerValue,quickSort(rightAry)); } var ary=[12.15.14.13.16.11]; var res=quickSort(ary); console.log(res); Copy the code

28. Insert sort

var ary = [34.56.12.66.12];
function insertSort(ary) {
   // Finally sorted array boxes
   var newAry = [];
   // Put the first item in the box. There is only one item in the box
 newAry.push(ary[0]);  // Insert each item in the array in turn  for (var i = 1; i < ary.length; i++) {  var getItem = ary[i];  // Compare each item in the new array at insertion time (from right to left)  for (var j = newAry.length - 1; j >= 0; j--) {  var newItemAry = newAry[j];  if (getItem >= newItemAry) {  // If the item is larger or equal, place it after the item  newAry.splice(j + 1.0, getItem);  // Stop the loop without continuing the comparison;  break;  }  if (j == 0) {  // If we are all at the top of the list, and we are not satisfied, then this is the smallest term and we insert it at the top of the list  newAry.unshift(getItem);  }  }   }  return newAry; } var res = insertSort(ary); console.log(res); Copy the code

29. Countdown case


let box = document.querySelector('#box'),
    content = document.querySelector('#content'),
    timer = null;
/ ** Every time the page is refreshed, you must get the time from the server to do the following* Ajax based asynchronous request, request success only* So it needs to be inside the callback function* To prevent callback hell problems, use promise* /  // Get the server time function getServerTime() {  return new Promise(resolve= > {  let xhr = new XMLHttpRequest;  xhr.open('get'.'./data.json? _ = ' + Math.random());  xhr.onreadystatechange = (a)= > {  if (xhr.readyState === 4 && /^(2|3)\d{2}$/.test(xhr.status)) {  let time = xhr.getResponseHeader('date');  time = new Date(time);  resolve(time);  }  }  xhr.send(null);  }); }  // Calculate the countdown according to the server time function computed(time) {  let target = new Date('2020/05/13 18:59:00'),  spanTime = target - time;  if (spanTime <= 0) {  // It is already the end of the time to buy  box.innerHTML = 'Start buying! '  clearInterval(timer);  return;  }  // Calculate how many hours, minutes, and seconds are included in the millisecond difference  let hour = Math.floor(spanTime / (60 * 60 * 1000));  spanTime = spanTime - hour * 60 * 60 * 1000;  let minutes = Math.floor(spanTime / (60 * 1000));  spanTime = spanTime - minutes * 60 * 1000;  let seconds = Math.floor(spanTime / 1000);  hour < 10 ? hour = '0' + hour : null;  minutes < 10 ? minutes = '0' + minutes : null;  seconds < 10 ? seconds = '0' + seconds : null;  content.innerHTML = `${hour}:${minutes}:${seconds}`; }  getServerTime().then(time= > {  // Get the server time  computed(time);  // Every 1 second, add 1  timer = setInterval((a)= > {  time = new Date(time.getTime() + 1000);  computed(time);  }, 1000); });  Copy the code

30. Random verification code

// Random captCHA: combination of digits and letters, (four digits and letters)
/ *=> 1 Prepare the verification code=> 2 Obtain the corresponding index value randomly=> 3 Obtain elements* / var code = document.getElementById("code"); var btn = document.getElementById("btn"); code.innerHTML = getCode(); btn.onclick = function () {  code.innerHTML = getCode(); } function getCode() {  var str = "qwertyuiopasdfghjklzxcvbnm" + "QWERTYUIOPASDFGHJKLZXCVBNM" + "0123456789";  var result = "";  //==> Range of index values: 0-- 61  while (result.length < 4) {  var index = Math.round(Math.random() * 61);  var item = str[index];  if (result.indexOf(item) == - 1) {  result += item;  }  }  return result; } Copy the code

31. TAB implementation

<body>
    <div id="app">
        <ul class='list'>
            <li class='active'>css</li>
            <li>js</li>
 <li>html</li>  </ul>  <ul class='con'>  <li class='active'>CSS styles</li>  <li>Js behavior</li>  <li>HTML structure</li>  </ul>  </div> </body> Copy the code
 * {
    margin: 0;
    padding: 0;
    list-style: none;
  }
  #app {  width: 500px;  margin: 20px auto;  }  .list {  overflow: hidden;  position: relative;  top: 1px;  }  .list li {  width: 100px;  float: left;  border: 1px solid # 333;  text-align: center;  margin-right: 10px;  height: 50px;  line-height: 50px;  cursor: pointer;  } .list li.active {  background-color: crimson;  border-bottom-color: crimson;  } .con li {  width: 100%;  border: 1px solid # 333;  height: 300px;  line-height: 300px;  text-align: center;  background-color: crimson;  display: none;  }  .con li.active {  display: block;  } Copy the code
let list = document.querySelector('.list'),
    lists = list.querySelectorAll('li'),
    con = document.querySelector('.con'),
    cons = con.querySelectorAll('li');
for (let i = 0; i < lists.length; i++) {
 lists[i].onclick = function () {  click(i);  }; } function click(index) {  for (let i = 0; i < lists.length; i++) {  lists[i].className = ' ';  cons[i].className = ' ';  }  lists[index].className = 'active';  cons[index].className = 'active'; } Copy the code
TAB

Third, summary

The above are common code snippets that I have summarized by reading other big names’ articles and adding my own knowledge. Finishing is not easy, if it is helpful to you can give the little sister a careful heart. In the later period, I will publish my learning summary and grow up with you ✌️

This article has been uploaded to GitHub👉. If you need to download children’s boots, you can print them here

This article is formatted using MDNICE