Array

Array common methods.

1. Array intersection

Regular array

const arr1 = [1.2.3.4.5.8.9],
arr2 = [5.6.7.8.9];
const intersection = arr1.filter(function (val) { 
    return arr2.indexOf(val) > -1; });console.log(intersection) / / [5, 8, 9]
Copy the code

The array object

Array objects currently only work with simple Number, String, and Boolan data types. Json.stringify is a shorthand method for comparing objects. See Tip 24 for a complete comparison of objects.

const arr1 = [
    { name: 'name1'.id: 1 }, 
    { name: 'name2'.id: 2 }, 
    { name: 'name3'.id: 3 }, 
    { name: 'name5'.id: 5}];const arr2 = [
    { name: 'name1'.id: 1 }, 
    { name: 'name2'.id: 2 }, 
    { name: 'name3'.id: 3 }, 
    { name: 'name4'.id: 4 }, 
    { name: 'name5'.id: 5}];const result = arr2.filter(function (v) {
    return arr1.some(n= > JSON.stringify(n) === JSONStringify (v))});console.log(result); // [{ name: 'name1', id: 1 },{ name: 'name2', id: 2 },{ name: 'name3', id: 3 },{ name: 'name5', id: 5 }]
Copy the code

2. Array union

Regular array

const arr1 = [1.2.3.4.5.8.9];const arr2 = [5.6.7.8.9];
const result = arr1.concat(arr2.filter(v= >! Arr1. Includes (v)));console.log(result) //[1, 2, 3, 4, 5, 8, 9, 6, 7]
Copy the code

The array object

const arr1 = [{ name: 'name1'.id: 1 }, { name: 'name2'.id: 2 }, { name: 'name3'.id: 3 }];
const arr2 = [{ name: 'name1'.id: 1 }, { name: 'name4'.id: 4 }, { name: 'name5'.id: 5 }];
let arr3 = arr1.concat(arr2);
let result = [];
let obj = [];
result = arr3.reduce(function (prev, cur, index, arr) {
  obj[cur.id] ? ' ' : obj[cur.id] = true && prev.push(cur);
  returnprev; } []);console.log(result); //[{ name: 'name1', id: 1 },{ name: 'name2', id: 2 },{ name: 'name3', id: 3 },{ name: 'name4', id: 4 },{ name: 'name5', id: 5 }]
Copy the code

3. Array difference set

The array arr1 does not have with respect to ARR2.

Regular array

const arr1 = [1.2.3.4.5.8.9];
const arr2 = [5.6.7.8.9];
const diff = arr1.filter(item= > !new Set(arr2).has(item))
console.log(diff) //[1, 2, 3, 4]
Copy the code

The array object

// Array of objects
let arr1 = [{ name: 'name1'.id: 1 }, { name: 'name2'.id: 2 }, { name: 'name3'.id: 3 }];
let arr2 = [{ name: 'name1'.id: 1 }, { name: 'name4'.id: 4 }, { name: 'name5'.id: 5 }];
let result = arr1.filter(function (v) {
    return arr2.every(n= > JSON.stringify(n) ! = =JSON.stringify(v))
})
console.log(result); // [ { name: 'name2', id: 2 }, { name: 'name3', id: 3 } ]
Copy the code

4. Array complement

A collection of two separate arrays

Regular array

const arr1 = [1.2.3.4.5.8.9];
const arr2 = [5.6.7.8.9];
const difference = Array.from(new Set(arr1.concat(arr2).filter(v= > !new Set(arr1).has(v) || !new Set(arr2).has(v)))) 
console.log(difference) //[1, 2, 3, 4, 6, 7]
Copy the code

The array object

let arr1 = [{ name: 'name1'.id: 1 }, { name: 'name2'.id: 2 }, { name: 'name3'.id: 3 }];
let arr2 = [{ name: 'name1'.id: 1 }, { name: 'name4'.id: 4 }, { name: 'name5'.id: 5 }];
let arr3 = arr1.concat(arr2);
let result = arr3.filter(function (v) {
    return arr1.every(n= > JSON.stringify(n) ! = =JSON.stringify(v)) || arr2.every(n= > JSON.stringify(n) ! = =JSON.stringify(v))
})
console.log(result); // [{ name: 'name2', id: 2 },{ name: 'name3', id: 3 },{ name: 'name4', id: 4 },{ name: 'name5', id: 5 }]
Copy the code

So to summarize, the difference set is the set that arr1 doesn’t have with respect to ARR2, and the complement is the set that both arrays don’t have.

5. Array deduplication

Regular array

console.log(Array.from(new Set([1.2.3.3.4.4)))/ / [1, 2, 3, 4]
console.log([...new Set([1.2.3.3.4.4]])/ / [1, 2, 3, 4]
Copy the code

The array object

const arr = [{ name: 'name1'.id: 1 }, { name: 'name2'.id: 2 }, { name: 'name3'.id: 3 }, { name: 'name1'.id: 1 }, { name: 'name4'.id: 4 }, { name: 'name5'.id: 5 }];
const result = [];
arr.forEach(item= >{
    !result.some(v= > JSON.stringify(v) === JSON.stringify(item)) && result.push(item)
})
console.log(result) //[{ name: 'name1', id: 1 },{ name: 'name2', id: 2 },{ name: 'name3', id: 3 },{ name: 'name4', id: 4 },{ name: 'name5', id: 5 }]
Copy the code

6. Array sort

Regular array

console.log([1.2.3.4].sort((a, b) = > a - b)); // [1, 2,3,4
console.log([1.2.3.4].sort((a, b) = > b - a)); / / descending,3,2,1 [4]
Copy the code

The array object

const arr1 = [{ name: "Rom".age: 12 }, { name: "Bob".age: 22 }].sort((a, b) = > { return a.age - b.age })/ / ascending
const arr2 = [{ name: "Rom".age: 12 }, { name: "Bob".age: 22 }].sort((a, b) = > { return -a.age + b.age })/ / descending
console.log(arr2) // [{ name: 'Bob', age:22 }, { name: 'Rom', age: 12 }]
console.log(arr1) // [ { name: 'Rom', age: 12 }, { name: 'Bob', age: 22 } ]
Copy the code

Both types of arrays can be sorted using sort, which is the browser’s built-in method;

By default, it returns a function with two arguments: (a, b) => a-b is in ascending order; (a, b) => b – A is in descending order.

The maximum value of 7.

Regular array

Math.max(... [1.2.3.4]) / / 4
Math.max.apply(this[1.2.3.4]) / / 4
[1.2.3.4].reduce((prev, cur, curIndex, arr) = > {
    return Math.max(prev, cur);
}, 0) / / 4
Copy the code

Take the maximum number of ids in an array object

const arr = [{ id: 1.name: 'jack'}, {id: 2.name: 'may'}, {id: 3.name: 'shawn'}, {id: 4.name: 'tony' }]
const arr1 = Math.max.apply(Math, arr.map(item= > { return item.id }))
const arr2 = arr.sort((a, b) = > { return b.id - a.id })[0].id
console.log(arr1) / / 4
console.log(arr2) / / 4
Copy the code

8. Array summing

Regular array

[1.2.3.4].reduce(function (prev, cur) {
  return prev + cur;
}, 0) / / 10
Copy the code

The array object

const sum = [{age:1}, {age:2}].reduce(function (prev, cur) {
  return prev + cur.age;
}, 0) / / 3
console.log(sum)
Copy the code

9. Array merge

Regular array

const arr1 =[1.2.3.4].concat([5.6]) / / [6]
const arr2 =[...[1.2.3.4],... [4.5]] / / [6]
const arrA = [1.2], arrB = [3.4]
const arr3 =[].concat.apply(arrA, arrB)/ / arrA value of [1, 2, 3, 4]
Copy the code

The array object

const arr4 = [{ age: 1 }].concat([{ age: 2 }])
const arr5 = [...[{ age: 1}],... [{age: 2 }]]
console.log(arr4) //[ { age: 1 }, { age: 2 } ]
console.log(arr5) // [ { age: 1 }, { age: 2 } ]
Copy the code

10. Whether the array contains values

Regular array

console.log([1.2.3].includes(4)) //false
console.log([1.2.3].indexOf(4)) //-1 if there is a swap index
console.log([1.2.3].find((item) = > item === 3)) //3 Return undefined if there is no value in the array
console.log([1.2.3].findIndex((item) = > item === 3)) //2 Returns -1 if there is no value in the array
Copy the code

The array object

const flag = [{age:1}, {age:2}].some(v= >JSON.stringify(v)===JSON.stringify({age:2}))
console.log(flag)
Copy the code

11. Each item in the array is satisfied

Regular array

[1.2.3].every(item= > { return item > 2 })
Copy the code

The array object

const arr = [{ age: 3 }, { age: 4 }, { age: 5 }]
arr.every(item= > { return item.age > 2 }) // true
Copy the code

12. One entry of the array satisfies

Regular array

[1.2.3].some(item= > { return item > 2 })
Copy the code

The array object

const arr = [{ age: 3 }, { age: 4 }, { age: 5 }]
arr.some(item= > { return item.age < 4 }) // true
Copy the code

13. Sort version numbers

Methods a

function sortNumber(a, b) {
  return a - b
}
const b = [1.2.3.7.5.6]
const a = ["1.5"."1.5"."1.40"."1.25"."1.1000"."1.1"];

console.log(a.sort(sortNumber)); // [1, 2, 3, 5, 6, 7]
console.log(b.sort(sortNumber)); / / [' 1.1000 ', 1.1 ' ', '1.25', 1.40 ' ', '1.5', 1.5 ' ']
Copy the code

The sort function does not apply to integers, because it compares strings with Unicode.

Method 2

// Assume that each section of the string is less than 5 characters long
/ / remove the array null | | Spaces
if (!Array.prototype.trim) {
  Array.prototype.trim = function () {
    let arr = []; this.forEach(function (e) {
      if (e.match(/\S+/)) arr.push(e);
    })
    returnarr; }}// Extract the numeric part
function toNum(a) {
  let d = a.toString();
  let c = d.split(/\D/).trim();
  let num_place = [""."0"."00"."000"."0000"], r = num_place.reverse();
  for (let i = 0; i < c.length; i++) {
    let len = c[i].length;
    c[i] = r[len] + c[i];
  }
  let res = c.join(' ');
  return res;
}

// Extract characters
function toChar(a) {
  let d = a.toString();
  let c = d.split(/\.|\d/).join(' ');
  return c;
}

function sortVersions(a, b) {
  let _a1 = toNum(a), _b1 = toNum(b);
  if(_a1 ! == _b1)return _a1 - _b1;
  else {
    _a2 = toChar(a).charCodeAt(0).toString(16);
    _b2 = toChar(b).charCodeAt(0).toString(16);
    return_a2 - _b2; }}let arr1 = ["10"."5"."40"."25"."1000"."1"];
let arr2 = ["1.10"."1.5"."1.40"."1.25"."1.1000"."1.1"];
let arr3 = ["1.10 c"."1.10 b"."1.10 C"."1.25"."1.1000"."1.10 A"];
console.log(arr1.sort(sortVersions)) //['1', '5', '10', '25', '40', '1000']
console.log(arr2.sort(sortVersions)) / / [' 1.1 ', 1.5 ' ', '1.10', 1.25 ' ', '1.40', 1.1000 ' ']
console.log(arr3.sort(sortVersions)) 1.10 1.10 / / [' A ', 'C', '1.10 b', '1.10 C', '1.25', 1.1000 ' ']

Copy the code

You can see that this function is compatible with integers, non-integers, and letters; Alphabetic sorting is based on Unicode, so 1.10 B comes after 1.10C

14. Object to array

Convert the key and value of an array to an array

Object.keys({ name: 'Joe'.age: 14 }) //['name','age']
Object.values({ name: 'Joe'.age: 14 }) 14] / / [' zhang SAN,
Object.entries({ name: 'Joe'.age: 14 }) / / [[name, 'zhang'], [14] age,]
Object.fromEntries([name, 'Joe'], [age, 14]) {name:' zhang SAN ',age:14}
Copy the code

15. Array to object

Converts the value of an array to the value of an object

const arrName = ['Joe'.'bill'.'Cathy']
const arrAge=['20'.'30'.'40']
const arrDec = ['description 1'.Description '2'.'describe 3']
const obj = arrName.map((item,index) = >{
  return { name: item, age: arrAge[index],dec:arrDec[index]}
})

console.log(obj) / / [{name: 'zhang' age: '20', dec: 'description 1}, {name: "bill", the age:' 30 ', dec: 'description 2}, {name:' Cathy 'age:' 40 ', dec: 'describe 3}]
Copy the code

16. Array deconstruction

const arr=[1.2]; // Be sure to add a semicolon after it, because the interpreter will assume that the array is being read without it
[arr[1], arr[0]] = [arr[0], arr[1]]./ / (2, 1]
Copy the code

Object

Object related methods.

17. Object variable properties

const flag = true;
const obj = {
    a: 0,
    [flag ? "c" : "d"] :2
};
// obj => { a: 0, c: 2 }
Copy the code

18. Delete unnecessary attributes of the object

const{ name, age, ... obj } = {name: 'Joe'.age: 13.dec: 'description 1'.info: 'information' }
console.log(name)  / / zhang SAN
console.log(age)  / / 13
console.log(obj)  // {dec: 'description 1', info:' info '}
Copy the code

19. Object nested attribute deconstruction

const { info:{ dec} } = { name: 'Joe'.age: 13.info: {dec: 'description 1'.info: 'information' }}
console.log(dec) / / description 1
Copy the code

20. Deconstruct object property aliases

const { name:newName } = { name: 'Joe'.age: 13 }
console.log(newName)  / / zhang SAN
Copy the code

21. Deconstruct the object property defaults

const { dec='This is the default dec value' } = { name: 'Joe'.age: 13 }
console.log(dec) // This is the default dec value
Copy the code

22. Intercepting objects

Intercepting objects with Object.defineProperty

Cannot intercept the value of an array

let obj = { name: ' '.age: ' '.sex: ' ' },
  defaultName = ["This is the name default value 1."."This is the default age of 1."."This is the gender default of 1."];
Object.keys(obj).forEach(key= > {
  Object.defineProperty(obj, key, { Vue 2.x intercepts the entire object and uses get to get the value and set the value
    get() {
      return defaultName;
    },
    set(value){ defaultName = value; }}); });console.log(obj.name); // [' This is the default name 1', 'this is the default age 1',' this is the default gender 1']
console.log(obj.age); // [' This is the default name 1', 'this is the default age 1',' this is the default gender 1']
console.log(obj.sex); // [' This is the default name 1', 'this is the default age 1',' this is the default gender 1']
obj.name = "This is the change of value 1.";
console.log(obj.name); // This is the change value 1
console.log(obj.age);  // This is the change value 1
console.log(obj.sex); // This is the change value 1

let objOne = {}, defaultNameOne = "This is the default value 2.";
Object.defineProperty(obj, 'name', {
  get() {
    return defaultNameOne;
  },
  set(value){ defaultNameOne = value; }});console.log(objOne.name); // undefined
objOne.name = "This is the change of 2.";
console.log(objOne.name); // This is the change value 2
Copy the code

Intercepting objects using a proxy

let obj = { name: ' '.age: ' '.sex: ' ' }
let handler = {
  get(target, key, receiver) {
    console.log("get", key); 
    return Reflect.get(target, key, receiver);
  },
  set(target, key, value, receiver) {
    console.log("set", key, value); // set age 24
    return Reflect.set(target, key, value, receiver); }};let proxy = new Proxy(obj, handler);
proxy.name = "Bill";
proxy.age = 24;
Copy the code

DefineProterty vs. Proxy:

  1. DefineProterty is an ES5 standard and Proxy is an ES6 standard.
  2. Proxy can listen to the array index assignment, change the array length change;
  3. Proxy is a listener object without deep traversal. DefineProterty is a listener attribute.
  4. Two-way data binding using defineProterty (core of vue2. X adoption)

23. Object deep copy

Json. stringify Deep clone object

  1. Unable to clone functions, RegExp and other special objects;
  2. Object constructor is discarded and all constructors point to Object;
  3. Object has a circular reference and an error is reported
const mapTag = '[object Map]';
const setTag = '[object Set]';
const arrayTag = '[object Array]';
const objectTag = '[object Object]';
const argsTag = '[object Arguments]';

const boolTag = '[object Boolean]';
const dateTag = '[object Date]';
const numberTag = '[object Number]';
const stringTag = '[object String]';
const symbolTag = '[object Symbol]';
const errorTag = '[object Error]';
const regexpTag = '[object RegExp]';
const funcTag = '[object Function]';

const deepTag = [mapTag, setTag, arrayTag, objectTag, argsTag];

function forEach(array, iteratee) {
  let index = -1;
  const length = array.length;
  while (++index < length) {
    iteratee(array[index], index);
  }
  return array;
}

function isObject(target) {
  const type = typeof target;
  returntarget ! = =null && (type === 'object' || type === 'function');
}

function getType(target) {
  return Object.prototype.toString.call(target);
}

function getInit(target) {
  const Ctor = target.constructor;
  return new Ctor();
}

function cloneSymbol(targe) {
  return Object(Symbol.prototype.valueOf.call(targe));
}

function cloneReg(targe) {
  const reFlags = /\w*$/;
  const result = new targe.constructor(targe.source, reFlags.exec(targe));
  result.lastIndex = targe.lastIndex;
  return result;
}

function cloneFunction(func) {
  const bodyReg = / (? <={)(.|\n)+(? =})/m;
  const paramReg = / (? < = \ () + (? =\)\s+{)/;
  const funcString = func.toString();
  if (func.prototype) {
    const param = paramReg.exec(funcString);
    const body = bodyReg.exec(funcString);
    if (body) {
      if (param) {
        const paramArr = param[0].split(', ');
        return new Function(... paramArr, body[0]);
      } else {
        return new Function(body[0]); }}else {
      return null; }}else {
    return eval(funcString); }}function cloneOtherType(targe, type) {
  const Ctor = targe.constructor;
  switch (type) {
    case boolTag:
    case numberTag:
    case stringTag:
    case errorTag:
    case dateTag:
      return new Ctor(targe);
    case regexpTag:
      return cloneReg(targe);
    case symbolTag:
      return cloneSymbol(targe);
    case funcTag:
      return cloneFunction(targe);
    default:
      return null; }}function clone(target, map = new WeakMap(a)) {

  // Clone the original type
  if(! isObject(target)) {return target;
  }

  / / initialization
  const type = getType(target);
  let cloneTarget;
  if (deepTag.includes(type)) {
    cloneTarget = getInit(target, type);
  } else {
    return cloneOtherType(target, type);
  }

  // Prevent circular references
  if (map.get(target)) {
    return map.get(target);
  }
  map.set(target, cloneTarget);

  / / clone set
  if (type === setTag) {
    target.forEach(value= > {
      cloneTarget.add(clone(value, map));
    });
    return cloneTarget;
  }

  / / clone map
  if (type === mapTag) {
    target.forEach((value, key) = > {
      cloneTarget.set(key, clone(value, map));
    });
    return cloneTarget;
  }

  // Clone objects and arrays
  const keys = type === arrayTag ? undefined : Object.keys(target);
  forEach(keys || target, (value, key) = > {
    if (keys) {
      key = value;
    }
    cloneTarget[key] = clone(target[key], map);
  });

  return cloneTarget;
}

console.log(
    clone({
      name: 'Joe'.age: 23.obj: { name: 'bill'.age: 46 },
      arr: [1.2.3]}))/ / {name: 'zhang' age: 23, obj: {name: "bill", the age: 46}, arr: [1, 2, 3]}
Copy the code

Object deep clone is actually compatible with Array, RegExp, Date, and Function types. Clone functions can use the re to fetch the Function body and parameters, and define a Function to assign values to the retrieved values

24. Whether objects are equal

If json.stringify transforms properties in a different order, it is not equal and does not support cloning of special objects such as functions and RegExp

function deepCompare(x, y) {
  var i, l, leftChain, rightChain;

  function compare2Objects(x, y) {
    var p;

    // remember that NaN === NaN returns false
    // and isNaN(undefined) returns true
    if (isNaN(x) && isNaN(y) && typeof x === 'number' && typeof y === 'number') {
      return true;
    }

    // Compare primitives and functions.     
    // Check if both arguments link to the same object.
    // Especially useful on the step where we compare prototypes
    if (x === y) {
      return true;
    }

    // Works in case when functions are created in constructor.
    // Comparing dates is a common scenario. Another built-ins?
    // We can even handle functions passed across iframes
    if ((typeof x === 'function' && typeof y === 'function') ||
      (x instanceof Date && y instanceof Date) ||
      (x instanceof RegExp && y instanceof RegExp) ||
      (x instanceof String && y instanceof String) ||
      (x instanceof Number && y instanceof Number)) {
      return x.toString() === y.toString();
    }

    // At last checking prototypes as good as we can
    if(! (xinstanceof Object && y instanceof Object)) {
      return false;
    }

    if (x.isPrototypeOf(y) || y.isPrototypeOf(x)) {
      return false;
    }

    if(x.constructor ! == y.constructor) {return false;
    }

    if(x.prototype ! == y.prototype) {return false;
    }

    // Check for infinitive linking loops
    if (leftChain.indexOf(x) > -1 || rightChain.indexOf(y) > -1) {
      return false;
    }

    // Quick checking of one object being a subset of another.
    // todo: cache the structure of arguments[0] for performance
    for (p in y) {
      if(y.hasOwnProperty(p) ! == x.hasOwnProperty(p)) {return false;
      } else if (typeofy[p] ! = =typeof x[p]) {
        return false; }}for (p in x) {
      if(y.hasOwnProperty(p) ! == x.hasOwnProperty(p)) {return false;
      } else if (typeofy[p] ! = =typeof x[p]) {
        return false;
      }

      switch (typeof (x[p])) {
        case 'object':
        case 'function':

          leftChain.push(x);
          rightChain.push(y);

          if(! compare2Objects(x[p], y[p])) {return false;
          }

          leftChain.pop();
          rightChain.pop();
          break;

        default:
          if(x[p] ! == y[p]) {return false;
          }
          break; }}return true;
  }

  if (arguments.length < 1) {
    return true; 
  }

  for (i = 1, l = arguments.length; i < l; i++) {

    leftChain = []; //Todo: this can be cached
    rightChain = [];

    if(! compare2Objects(arguments[0].arguments[i])) {
      return false; }}return true;
}

const obj1 = { 
  name: 'Joe'.age: 23.obj: { name: 'bill'.age: 46 }, 
  arr: [1.2.3].date:new Date(23),
  reg: new RegExp('abc'),
  fun: () = >{}}const obj2 = { 
  name: 'Joe'.age: 23.obj: { name: 'bill'.age: 46 }, 
  arr: [1.2.3].date: new Date(23),
  reg: new RegExp('abc'),
  fun: () = >{}}console.log(deepCompare(obj1,obj2)) // true

Copy the code

To determine whether objects are equal, we are essentially dealing with the equality of the special types Array, Date, RegExp, Object, and Function

25. Objects are converted to strings

Convert an Object to a string by string +Object (actually calling.toString())

'the Math object:' + Math.ceil(3.4)                // "the Math object:4"
'the JSON object:' + {name:"Cao cao}              // "the JSON object:[object Object]"
Copy the code

Overrides the toString and valueOf methods of an object from defining the type conversion of the object

2  * { valueOf: () = >'4' }                / / 8
'J' + { toString: () = >'ava' }                // "Java"
Copy the code

When + is used to concatenate strings, when an object has both toString and valueOf methods, JS resolves this ambiguity by blindly using valueOf to cast the object to a number through valueOf and to a string through toString

' ' + {toString:() = >'S'.valueOf:() = >'J'}  //J
Copy the code

Function

Function dependent method

26. Function implicitly returns a value

(() = >3) ()/ / 3
(() = >(
   3()))Copy the code

Function omitting curly braces, or changing curly braces to curly braces, ensures that the code is evaluated as a single statement

27. The function is self-executing

const Func = function() {} ();/ / the commonly used

(function() {}) ();/ / the commonly used
(function() {} ());/ / the commonly used
[function() {} ()];new function() {};
new function() {} ();void function() {} ();typeof function() {} ();delete function() {} (); +function() {} (); -function() {} (); ~function() {} (); !function() {} ();Copy the code

28. The function executes asynchronously

Promise

Promise.reject('This is the second reject').then((data) = >{
  console.log(data)
}).catch(data= >{
  console.log(data) // This is the second reject value
})
Copy the code

Generator

function* gen(x) {
  const y = yield x + 6;
  return y;
}

// If used in another expression, the yield should be placed inside ()
// Do not add () to the right of =
function* genOne(x) {
  const y = 'This is the first yield execution:The ${yield x + 1}`;
  return y;
}

const g = gen(1);
// Executing Generator returns an Object, instead of returning the value after return as normal functions do
g.next() // { value: 7, done: false }
The next method, which calls the pointer, executes from the head of the function or where it was last stopped until the next yield expression or return is paused, executing the yield line
// An Object is returned,
// value is the value after yield, and done indicates whether the function is finished
g.next() // { value: undefined, done: true }
// Since the last line of return y is executed, done is true
Copy the code

Async/Await

function getSomething() {
    return "something";
}
async function testAsync() {
    return Promise.resolve("hello async");
}
async function test() {
    const v1 = await getSomething();
    const v2 = await testAsync();
    console.log(v1, v2); / / something and hello async
}
test();
Copy the code

String

String method

29. String reversal

function reverseStr(str = "") {
  return str.split("").reduceRight((t, v) = > t + v);
}

const str = "reduce123";
console.log(reverseStr(str)); // "321recuder"
Copy the code

30. Url parameter serialization

Pass the object serialized as a URL parameter

function stringifyUrl(search = {}) {
  return Object.entries(search).reduce(
    (t, v) = > `${t}${v[0]}=The ${encodeURIComponent(v[1])}& `.Object.keys(search).length ? "?" : ""
  ).replace($/ / &."");
}

console.log(stringifyUrl({ age: 27.name: "YZW" })); / / "? age=27&name=YZW"
Copy the code

31. Deserialize url parameters

Search is used to retrieve the parameters passed by the route and deserialize the object

function parseUrlSearch() {
  const search = '? age=25&name=TYJ'
  return search.replace(/ (a ^ \? |(&$)/g."").split("&").reduce((t, v) = > {
    const [key, val] = v.split("=");
    t[key] = decodeURIComponent(val);
    return t;
  }, {});
}

console.log(parseUrlSearch()); // { age: "25", name: "TYJ" }
Copy the code

32. Convert to a string

const val = 1 + ""; // Convert by + '" empty string
console.log(val); / / "1"
console.log(typeof val); // "string"

const val1 = String(1);
console.log(val1); / / "1"
console.log(typeof val1); // "string"
Copy the code

Number

Digital processing

33. Digital thousandths

Method one:

function thousandNum(num = 0) {
  const str = (+num).toString().split(".");
  const int = nums= > nums.split("").reverse().reduceRight((t, v, i) = > t + (i % 3 ? v : `${v}, `), "").replace(/^,|,$/g."");
  const dec = nums= > nums.split("").reduce((t, v, i) = > t + ((i + 1) % 3 ? v : `${v}, `), "").replace(/^,|,$/g."");
  return str.length > 1 ? `${int(str[0])}.${dec(str[1])}` : int(str[0]);
}

thousandNum(1234); // "1,234"
thousandNum(1234.00); // "1,234"
thousandNum(0.1234); / / 0.123 ", 4"
console.log(thousandNum(1234.5678)); / / ", 1234567, 8"
Copy the code

Method 2

console.log('1234567890'.replace(/\B(? =(\d{3})+(? ! \d))/g.","))
console.log((1234567890).toLocaleString())
Copy the code

34. String to number

Methods a

To convert to a number with *1, you’re actually calling the.valueof method

'32' * 1            / / 32
'ds' * 1            // NaN
null * 1            / / 0
undefined * 1    // NaN
1  * { valueOf: () = >'3' }        / / 3
Copy the code

Method 2

+ '123'            / / 123
+ 'ds'               // NaN
+ ' '                    / / 0
+ null              / / 0
+ undefined    // NaN
+ { valueOf: () = >'3' }    / / 3
Copy the code

35. Check if decimals are equal

I’m sure some people will say this isn’t easy, just use ‘===’ to compare actually 0.1+0.2! ==0.3, because computers can’t accurately represent floating point numbers like 0.1 and 0.2, so they don’t add up to 0.3

Number.EPSILON=(function(){   // Resolve compatibility issues
    return Number.EPSILON?Number.EPSILON:Math.pow(2, -52); }) ();// This is a self-calling function that checks and returns a result as soon as the JS file is loaded into memory
function numbersequal(a,b){ 
    return Math.abs(a-b)<Number.EPSILON;
  }
// Then decide
const a=0.1+0.2, b=0.3;
console.log(numbersequal(a,b)); // this is true
Copy the code

36. Two-bit operators

Two-bit operators are faster than math.floor (), math.ceil ()

~ ~7.5                / / 7
Math.ceil(7.5)       / / 8
Math.floor(7.5)      / / 7~ ~ -7.5          / / - 7
Math.floor(-7.5)     / / - 8
Math.ceil(-7.5)      / / - 7
Copy the code

So for negative numbers, the two-bit operator is the same as math.ceil, and for positive numbers it is the same as math.floor

37. Integer and parity judgment

integer

3.3 | 0         / / 3
-3.9 | 0        // -3

parseInt(3.3)  / / 3
parseInt(-3.3) // -3

// Round up
Math.round(3.3) / / 3
Math.round(-3.3) // -3

// round up
Math.ceil(3.3) / / 4
Math.ceil(-3.3) // -3

// round down
Math.floor(3.3) / / 3
Math.floor(-3.3) / / - 4
Copy the code

Judge odd and even

const num=5; !!!!! (num &1) // true!!!!! (num %2) // true
Copy the code

Boolean

Boolean value method

38. Determine the data type

function dataTypeJudge(val, type) {
  const dataType = Object.prototype.toString.call(val).replace(/\[object (\w+)\]/."$1").toLowerCase();
  return type ? dataType === type : dataType;
}
console.log(dataTypeJudge("young")); // "string"
console.log(dataTypeJudge(20190214)); // "number"
console.log(dataTypeJudge(true)); // "boolean"
console.log(dataTypeJudge([], "array")); // true
console.log(dataTypeJudge({}, "array")); // false
Copy the code

Identifiable type: Undefined, NULL, string, Number, Boolean, array, object, symbol, date, RegEXP, function, AsyncFunction, arguments, set, map, WeakSet, we akmap

39. Use Boolean to filter array false values

const compact = arr= > arr.filter(Boolean)
compact([0.1.false.2.' '.3.'a'.'e' * 23.NaN.'s'.34])  //[ 1, 2, 3, 'a', 's', 34 ]
Copy the code

40. Short-circuit operation

| | (or)

const flag = false || true //true
// The default value can be given when a value is false
const arr = false| | []Copy the code

&& (with)

const flag1 = false && true //false
const flag2 = true && true //true
Copy the code

41. The switch shorthand

You can use objects instead of switches to improve code readability

switch(a) {
  case 'Joe':
    return 'the age is 12'
  case 'bill':
    return 'age is 120'
}

// Replace with an object
const obj ={
  'Joe': 'age12'.'bill': 'age120',}console.log(obj['Joe'])
Copy the code