Prototype chain inheritance

 function Animal(){
            this.color=['red','pink'];
        }
        Animal.prototype.getColor=function(){
            return this.color;
        }
        function Dog(){

        }
        Dog.prototype=new Animal();
        let dog1=new Dog();
        dog1.color.push('blue');
        let dog2=new Dog();
        console.log(dog2.color)
Copy the code

Constructor inheritance

function Animal(name){ this.name=name; this.getName=function(){ return this.name; } } function Dog(name){ Animal.call(this,name); Dog. Prototype =new animal ();Copy the code

Parasitic combinatorial inheritance

function objectCopy(obj) { function Fun() { }; Fun.prototype = obj; return new Fun(); } function inheritPrototype(child, parent) { let prototype = objectCopy(parent.prototype); Prototype. Constructor = child; // Add object Child. Prototype = prototype; } function Parent(name) {this.name = name; this.friends = ["rose", "lily", "tom"] } Parent.prototype.sayName = function () { console.log(this.name); } function Child(name, age) { Parent.call(this, name); this.age = age; } inheritPrototype(Child, Parent); Child.prototype.sayAge = function () { console.log(this.age); } let child1 = new Child("yhd", 23); child1.sayAge(); // 23 child1.sayName(); // yhd child1.friends.push("jack"); console.log(child1.friends); // ["rose", "lily", "tom", "jack"]Copy the code

Function image stabilization

   function debonce(func,wait){
            var timeout;
            return function(){
                var context=this;
                var args=srguments;
                clearTimeout(timeout)
                timeout=setTimeout(function(){
                    func.apply(context,args)
                },wait)
            }
        }
       
Copy the code

Function of the throttle

function throttle(func,wait){ var context,args; var previous=0; return function(){ var now=new Date(); context=this; args=arguments; if(now-previous>wait){ func.apply(context.args); orevious=now; }}}Copy the code

Depth copy of the function

Function shallowCopy(obj){if(typeof obj! =='object') return; let newObj=obj instanceof Array? [] : {}; For (var k in obj){if(obj.hasownProperty (k)){newObj[k]=obj[k]}} return newObj} // deep copy const isObject=(target)=>(typeof target ==='object'||typeof target ==='function')&& target! ==null; function deepClone(target, map = new WeakMap()) { if (map.get(target)) { return target; } // Get the constructor for the current value: get its type let constructor = target.constructor; / / check whether the current object target and regular, the Date format object matching the if (/ ^ (RegExp | Date) $/ i.t est (constructor. Name)) {/ / create a new special object (regular classes/Date) return the instance of the new constructor(target); } if (isObject(target)) { map.set(target, true); Const cloneTarget = array.isarray (target)? [] : {}; for (let prop in target) { if (target.hasOwnProperty(prop)) { cloneTarget[prop] = deepClone(target[prop], map); } } return cloneTarget; } else { return target; }}Copy the code

Data type judgment

  function typeOf(obj){
           let res=Object.prototype.toString.call(obj).split(' ')[1];
           res=res.substring(0,res.length-1).toLowerCase();
           return res
       }
       typeOf([]);
       typeOf({});
       typeOf(new Date);
Copy the code

Array flattening

var arr1=[1, [2, [3]]]; function flatten(arr){ var result=[]; for(var i=0; i<arr.length; i++){ if(Array.isArray(arr[i])){ result=result.concat(flatten(arr[i])) }else{ result=result.push(arr[i]) } } return result; } //es6 function flatten(arr){ while(arr.some(item=>Array.isArray(item))){ arr=[].concat(... arr) } return arr; }Copy the code

Array to heavy

Var arr = var result,1,2,2,0 [1] = []; for(var i=0; i<arr.length; i++){ if(! result.includes(arr[i])){ result.push(arr[i]) } } console.log(result); Var unique => [...new Set(arr)]Copy the code

call

Function.prototype.call2 = function (context) { var context = context || window; context.fn = this; var args = []; for(var i = 1, len = arguments.length; i < len; i++) { args.push('arguments[' + i + ']'); } var result = eval('context.fn(' + args +')'); delete context.fn return result; } the author: the sea I come links: https://juejin.cn/post/6946022649768181774 source: the nuggets copyright owned by the author. Commercial reprint please contact the author for authorization, non-commercial reprint please indicate the source.Copy the code

bind

Function.prototype.bind2 = function (context) { var self = this; var args = Array.prototype.slice.call(arguments, 1); var fNOP = function () {}; var fBound = function () { var bindArgs = Array.prototype.slice.call(arguments); return self.apply(this instanceof fNOP ? this : context, args.concat(bindArgs)); } fNOP.prototype = this.prototype; fBound.prototype = new fNOP(); return fBound; } the author: the sea I come links: https://juejin.cn/post/6946022649768181774 source: the nuggets copyright owned by the author. Commercial reprint please contact the author for authorization, non-commercial reprint please indicate the source.Copy the code

apply

Function.prototype.apply2 = function (context, arr) { var context = context || window; context.fn = this; var result; if (! arr) { result = context.fn(); } else { var args = []; for (var i = 0, len = arr.length; i < len; i++) { args.push('arr[' + i + ']'); } result = eval('context.fn(' + args + ')') } delete context.fn return result; } the author: the sea I come links: https://juejin.cn/post/6946022649768181774 source: the nuggets copyright owned by the author. Commercial reprint please contact the author for authorization, non-commercial reprint please indicate the source.Copy the code

Promise.all

Promise.all rules look like this:

All Promsie passed in are fulfilled, and a new Promise consisting of their values is returned with the state of fulfilled; As long as one Promise is Rejected, a new Promsie with the Rejected state is returned, and its value is the value of the first Rejected Promise. As long as either Promise is pending, a new Promise in a pending state is returned;

Promise.all = function(promiseArr) { let index = 0, result = [] return new Promise((resolve, reject) => { promiseArr.forEach((p, i) => { Promise.resolve(p).then(val => { index++ result[i] = val if (index === promiseArr.length) { resolve(result) } }, Err = > {reject (err)})})})} the author: the sea I come links: https://juejin.cn/post/6946022649768181774 source: the nuggets copyright owned by the author. Commercial reprint please contact the author for authorization, non-commercial reprint please indicate the source.Copy the code

Quick sort

const quickSort = (arr) =>{ if(arr.length <= 1){ return arr }; let pivotIndex = Math.floor(arr.length/2); let pivot = arr.splice(pivotIndex,1)[0] ; // let left =, right = []; for(let i = 0; i<arr.length; i++){ if(arr[i]<pivot){ left.push(arr[i]); }else{ right.push(arr[i]); } } return quickSort(left).concat([pivot],quickSort(right)); }Copy the code

An array of bubble

Bubble sort: Pairwise comparison of multiple items over and over again, n(n-1)/2

for (var i = 1; i < arr.length; For (var j = arr. Length - 1; j >= i; If (arr[j] < arr[j-1]) {var temp = arr[j]; var temp = arr[j]; arr[j] = arr[j - 1]; arr[j - 1] = temp; } } console.log(arr); } console.log(arr);Copy the code

Fibonacci numbers

/ / write a function, the function of this function is to return the Fibonacci sequence in the subscript for the item value n function fib (n) {/ / sequence of subscript to 0, and the subscript 1 item value is 1 if (n = = 0 | | n = = 1) return 1; Return fib(n-1) + fib(n-2); return fib(n-1) + fib(n-2); } // Write a loop to calculate the first 15 terms of the Fibonacci sequence for (var I = 0; i < 15; i++) { console.log(fib(i)); }Copy the code