Image stabilization

let debounce = (fn,wait) = >{
    let timer = 0;
    return (. args) = >{
        if(timer)clearTimeout(timer);
        timer = setTimeout(() = >{
            fn.apply(this,args)
        },wait)
    }
}
Copy the code

The throttle

const throttle = (fn, wait) = > {
    let finished = true;
    return (. args) = > {
        if(! finished)return;
        finished = false;
        setTimeout(() = > {
            fn.apply(this, args);
            finished = true;
        }, wait);
    };
};
Copy the code

Deep copy

// The data type to be copied can be classified as basic data type,
const deepClone = (target, map = new Map(a)) = > {
    // Start with the basic data types
    if((typeoftarget ! = ='object'|| target ! = ='function') || target ! = =null) return target;
    // Determine the specific reference data type
    let type = Object.prototype.toString.call(target);
    let cloneTarget;

}
Copy the code

New additions to ES6

Some subtle extensions

letandconst:varThere are variable promotions and are bound globallywindowArrow function features: parameter only one can be omitted parentheses, function body only one sentence, can be omitted braces, write on a line, do not writereturn, noarguments,thisOf the external scopethis, cannot be used as constructors// Extend the operator
Copy the code

Object to expand

Keys (obj) : array of all keys of an object VALUES (obj) : array of all values of an object Entries (obj) : two-dimensional array of all keys and values of an object. Format: [[k1, v1], [k2, v2],...Copy the code

Extension of arrays

Find () returns to find the first eligible array member, otherwise returnsundefined. [1.4, -5.10].find((n) = > n < 0)  -5FindIndex () returns the first eligible array member index value, or - if none exists1. [1.5.10.15].findIndex((value) = >  value > 9) 2

Array.from() converts a pseudo-array to an arraylet arr = Array.from({0: 'a'.1: 'b'.2: 'c'.length: 3});// ['a', 'b', 'c']The includes() method determines whether an array contains a value [1.4.3.9].includes(4.2);// select * from 2; // select * from 2Array instance flat(), flatMap() [1[2[3]]].flat(Infinity) / / [1, 2, 3]The flatMap() method performs a function on each member of the original array, and then flat() on the array of returned values.// Equivalent to [[2, 4], [3, 6], [4, 8]].flat()
[2.3.4].flatMap((x) = > [x, x * 2]) // [2, 4, 3, 6, 4, 8]

Copy the code

String extension

Strings include (), startsWith(), endsWith(),repeat() includes(STR, [position]) StartsWidth (STR, [position]) returns a Boolean indicating whether the parameter string is in the head of the original string or at the specified position endsWith(STR, [position]) returns a Boolean indicating whether the parameter string is found. Indicates whether the argument string is at the end of the original string or at the specified position.console.log('hello world'.includes('e'.2)); // false starts at position 2 and looks for e
console.log('hello world'.includes('e')); // true
console.log('hello world'.startsWith('h')); // If the position is not specified, see if it starts with h, return true
console.log('hello world'.startsWith('l'.2)); // The character at the specified position is l, which returns true
console.log('hello world'.endsWith('d')); // No specified position, ending with d, returns true
console.log('hello world'.endsWith('r'.9)); // The character at the specified position is r, which returns true

let html = '<li>itheima</li>';
html = html.repeat(10);
Copy the code

Closures implement modularity

Realize chain operation

To implement a chained call, a function must return an instance, such as an array map.

// Create a class
class Person{
  setName(){
    this.name = name;
    return this;
  }
  setAge(){
    this.age = age;
    return this; }};/ / instantiate
var person= new Person();
person.setName("Mary").setAge(20); Disadvantages of chain operations: For example, if a method on my prototype wants to return a value, it can't be called in chain, or it can only be called last. The nice thing about chain operations is that they make the flow of asynchronous programming much cleaner and are not coupled to each other as callback functions are in jQuery and ES6PromiseAnd it was with this idea in mind,PromiseEach asynchronous task returns onePromiseObject that specifies the callback function through the then method.Copy the code

Attribute. And []

thisXXX andthis['xxx'+ a] is the same as the JS engine only at the beginningthis['xxx'], now writethisIn fact, the JS engine will also be converted internallythis['xxx']
Copy the code

Common operators

Arithmetic operator

Addition, subtraction, multiplication and division mod, autoincrement, autosubtractionCopy the code

The assignment operator

=, + =, = =, *, /, % = =, bitwise and assignment (& =), bitwise or assignment (| =), according to the assignment (~ =),Copy the code

An operator

Bitwise and (&), bitwise or (|), bitwise not (~) and the bitwise xor (^), < < left, > > moves to the right, > > > signed moves to the right Binary:512 256 64 32 | 16 8 4 2 1(left and right hand) negative: The number is positive1and0Interchange plus1   -9= >1001= >0110+1= >1111 1111 1111 1111 1111 1111 1111 0111Bitwise NOT (NOT) ~25= > - (25) -1= > -26~ ~25= > - (25) -1= > -26= > - (-26) -1= >25The bitwise AND (AND)25 & 3= >11001 & 00011=> Search for simultaneous existence1The number of digits of1= >00001= >1The bitwise OR (OR)25 | 3= >11001 & 00011= > there1The number of digits of theta1= >11011= >27Bitwise XOR25 ^ 3= >11001 & 00011= > there1The number of digits of theta1If both exist, =>11010= >26
var a=10,b=9; a ^= b, b ^= a, a ^= b; //a=9,b=10< < left -2<<5= >2The binary of10Move it all the way5A = >0000010-> 1000000= > -64>> Right shift this operator moves the first operand to the right by the specified number of digits. Bits removed to the right are discarded -9 >> 2= >1001 -> 10= > -2>>> Sign right shift positive numbers >>> the result is the same as >>, negative numbers >>> values will be large rounded: ~~3.9= >3
3.9 | 0= >3
3.9 ^ 0= >3
3.9 << 0= >3
Copy the code

Comma operator (,)

The ability to execute the operand on the left, then the operand on the right, and finally return the value of the right-hand operand. a = (b =1,c = 2);  // Execute and assign consecutively
console.log(a);  / / return 2
console.log(b);  / / returns 1
console.log(c);  / / return 2
Copy the code

Keywords that you need to pay attention to

in

In addition to cooperateforTraversing the object, you can also determine whether an attribute belongs to an object (including the prototype on the prototype chain) as follows:"make" in {make: "Honda".model: "Accord".year: 1998}  // returns true
0 in ["redwood"."bay"."cedar"."oak"."maple"]        // returns true
"length" in trees // returns true (length is an Array property)
Copy the code

instanceof

Can an object find the prototype of another object through the prototype chain

How to bind Class and Style dynamically?

Class

Object syntax: <div v-bind:class="{ active: isActive, 'text-danger': hasError }"></div>

data: {
  isActive: true.hasError: false} copy code array syntax: <div v-bind:class="[isActive ? activeClass : '', errorClass]"></div>

data: {
  activeClass: 'active'.errorClass: 'text-danger'
}
Copy the code

style

<div V-bind :style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>

data: {
  activeColor: 'red'.fontSize: 30} Array syntax: <div v-bind:style="[styleColor, styleSize]"></div>

data: {
  styleColor: {
     color: 'red'
   },
  styleSize: {fontSize:'23px'}}Copy the code

JavaScript statement identification

for- Loop the code block a certain number of times according to the conditionlet i = 0;
for(; i<10;) { i++ }Copy the code
while- Loop the code block a certain number of times according to the conditionlet j = 0;
while(j<10){
    i++
}
Copy the code
Forin - Used to traverse the properties of an objectCopy the code
Dowhile - Executes a block of statements and loops the block a certain number of times conditionallyvar text = ""
var i = 0;
do {
    i++;
} while (i < 5);
Copy the code

Print primes up to 100

// A number divisible only by itself and 1
let arr = [];
for(let i = 2,count = 0; i<100; i++){ // First of all, 1 is definitely not, nor is 100
    for(let j = 1; j<=i; j++)if(i%j==0)count++;// If the mod is 0, count adds up
    if(count === 2)arr.push(i);// A prime number is a number that is divisible only by 1 and itself if the mod is only twice
    count = 0;// Reset times
}
Copy the code

Fibonacci numbers

function Fibonacci(n){
    let arr = []
    let n1 = 1, n2 = 1;
    arr.push(n1,n2)
    for (let i = 2; i < n; i++){
        [n1, n2] = [n2, n1 + n2];
        arr.push(n2)
    }
    return arr;
}
Fibonacci(10)


function Fibonacci2 (n , ac1 = 1 , ac2 = 1) {
  if( n <= 1 ) {return ac2};
  return Fibonacci2 (n - 1, ac2, ac1 + ac2);
}
Copy the code

Caller and arguments.callee and fn.length

argumentsIt's a collection of arguments, it's an array of classes, and it has a property called callee, which is the function itself, often used inside an anonymous function to get the anonymous function itselffunction fn(){
    console.log(arguments.callee === fn)//true
    console.log(arguments.callee.length)//0 parameter length
    console.log(arguments.length)//3 Argument length
}
fn(1.2.3)




function f1(){
    f2()
}
function f2(){
    console.log(f2.caller)//f1(){} points to who is calling its function} f1() in strict mode caller, callee,argumentsCan't be passedCopy the code

Json.stringify () and toString()

  1. ToString () is converted to a string, so there is no []
  2. Json. stringify is converted to a JSON string with a []

The iteration

  1. JavaScript’s built-in iterables are String, Array, Map, and Set.
  2. When iterating over these data types (such as for… Of), JavaScript internally (without arguments) calls the @@iterator method on these data type prototypes (accessible through the constant symbol. iterator), and returns an iterator protocol object that gets the value to be iterated over.
  3. Some built-in syntactic constructs — like for… Of loops, expansion syntax, yield*, and destruct assignment — their internal implementations use the same iteration protocol:
[...someString]                              // ["h", "i"]
Copy the code
[] [Symbol.iterator]() + ' ' //"[object Array Iterator]"
' '[Symbol.iterator]() + ' ' //"[object String Iterator]"
new Map(to)Symbol.iterator]() + ' ' //"[object Map Iterator]"
new Set(to)Symbol.iterator]() + ' ' //"[object Set Iterator]"

let iterator1 = [][Symbol.iterator]();  Return an iterator
let iterator2 = ' '[Symbol.iterator]();  Return an iterator
let iterator3 = new Map(to)Symbol.iterator]();  Return an iterator
let iterator4 = new Set(to)Symbol.iterator]();  Return an iterator

iterator1.next();    // { value: xxx, done: false }
iterator1.next();    // { value: xxx, done: false }.Copy the code

To make an object iterable:

There is no @@iterator method on the Object, so the Object is not iterable. However, we can define a [symbol. iterator] method on the Object prototype to make the Object iterable.

When there is no custom iterable method for an object:

var myIterable = {};
for( key of myIterable){
    console.log(key)
}
//Uncaught TypeError: myIterable is not iterable
Copy the code

When customizing iterable methods for objects:

var myIterable = {};
myIterable[Symbol.iterator] = function* () {
    yield 1;
    yield 2;
    yield 3;
};
for( key of myIterable){
    console.log(key)
}
/ / 1
/ / 2
/ / 3
Copy the code

That is, we can change the method of the iterable or make any object iterable.

To make a newly created instance of a class iterable:

When there is no custom iterable method for a class instance:

class SimpleClass {
  constructor(data) {
    this.data = data
  }
}
const simple = new SimpleClass([1.2.3.4.5])
for (const val of simple) {
  console.log(val)
}
//Uncaught TypeError: simple is not iterable
Copy the code

When customizing iterable methods for class instances:

class SimpleClass {
  constructor(data) {
    this.data = data
  }
  [Symbol.iterator]() {
    return {
      next: () = > {
        if (index < this.data.length) {
          return {value: this.data[index++], done: false}}else {
          return {done: true}
        }
      }
    }
  }
}

const simple = new SimpleClass([1.2.3.4.5])

for (const val of simple) {
  console.log(val)   //'1' 2' 3' 4' 5'
}
Copy the code

Simple iterator

function makeIterator(array) {
    let nextIndex = 0;
    return {
       next: function () {
           return nextIndex < array.length ? {
               value: array[nextIndex++],
               done: false}, {done: true}; }}; }let it = makeIterator(['oh'.'ah']);

console.log(it.next().value); / / 'hey'
console.log(it.next().value); / / 'ah'
console.log(it.next().done);  // true
Copy the code