Yesterday, I was reading the authoritative guide and saw a method that I thought was elegant, so I thought to record it (my dream is to write elegant code with poetry). In the Js world, there are some operations that you can’t understand, but are elegant. If there are mistakes, welcome criticism and correction! (Click “like” before you watch it to make it a good habit hahaha)

1. Determine to be empty

  • Direct writing
    if(a == undefined) a = [];
    
    if(params.success){
        params.success(res);
    }
    
Copy the code
  • Elegant writing
a = a || []; params.success&&params.success(res); // Note 1.ifVar, =, etc, can not appear in the assignment definition statement, can use elegant writingifThere can be more than one method call inside, but only inside a methodtrueReturn value (this usage is not significant)Copy the code

Problem: When we write JS code, we often encounter complex logic judgment, usually we can use if/else or switch to achieve multiple conditional judgment, but there is a problem, as the logic complexity increases, the code of if/else/switch will become more and more bloated, more and more difficult to understand.

2. Multi-condition judgment

  • The small white writing

    var Statistics = function(){
      console.log('execution')
    }
    switch (currentTab) 
    {
       case 0:
           Statistics();
           break;
      case 1:
         Statistics();
           break;
       case 2:
           Statistics();
         break;
        case 3:
         Statistics();
         break;
    }
Copy the code
  • Elegant writing
// Use the judgment condition as the attribute name and the processing logic as the attribute value of the objectfunction(){
      console.log('execution')
    }
    const comparativeTotles = new Map([
        [0,Statistics],
        [1,Statistics],
        [2,Statistics],
        [3,Statistics]
     ])
    let map = function(val){
          return comparativeTotles.get(val)
    } 
    letgetMap = map(1); // Return undefined if not foundif(! getMap){ console.log('Not found')}else{
        concaozuole.log('Perform operation')
          getMap()
    }
Copy the code
  • if else
@param {number} status Active status: 1 invoicefailed 2 invoicefailed 3 Invoicesuccessful 4 Merchandise sold out 5 Inventory not invoiceable * @param {string} identity: */ const onButtonClick = (status, identity) => {if (identity == 'guest') {
    if(status == 1) {//else if(status == 2) {// function processing}else if(status == 3) {// function processing}else if(status == 4) {// function processing}else if(status == 5) {// function processing}else{// function processing}}else if (identity == 'master') {
    if(status == 1) {//else if(status == 2) {// function processing}else if(status == 3) {// function processing}else if(status == 4) {// function processing}else if(status == 5) {// function processing}else{// function processing}}}Copy the code
  • After the change
// Using the array loop property, all the qualified logic is executed, so you can execute both the public logic and the separate logic. constfunctionA = ()=>{/*doSTH */} // single business logic constfunctionB = ()=>{/*doSTH */} // single business logic constfunctionC = ()=>{/*send log*/ / const actions = new Map([[)'guest_1', () = > {functionA }],
    ['guest_2', () = > {functionB }],
    ['guest_3', () = > {functionC }],
    ['guest_4', () = > {functionA }],
    ['default', () = > {functionC }], //... ] @param {string} identity: guest state master state * @param {number} status Active state: */ const onButtonClick = (identity, status) => {let action = actions.get(`${identity}_${status}`) || actions.get('default')
  action.call(this)
}
Copy the code

Three, ‘SAO’ operation

1. Generate a random ID

// Generate a random alphanumeric string of length 10 math.random ().toString(36).substring(2);Copy the code

2. Update the current time every second

setThe Interval (() = > document. Body. InnerHTML = new Date (). ToLocaleString (). Slice (10, 18))Copy the code

3. Generate a random hexadecimal color code like # FFFFFF

The '#' + Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, '0');
Copy the code

4. Return to the keyboard

// Return a keyboard graphic with a string (_=>[..."`1234567890-=~~QWERTYUIOP[]\~ASDFGHJKL; '~~ZXCVBNM,./~"].map(x=>(o+=`/${b='_'.repeat(w=x\|`,m+=y+(x+' ').slice(0,w)+y+y,n+=y+b+y+y,l+='__'+b)[73]&&(k.push(l,m,n,o),l=' ',m=n=o=y),m=n=o=y='|',p=l=k=[])&&k.join`
`)()
Copy the code

5. Round gracefully

Var a = 2.33 ~ ~ -- -- -- -- > 2 var b = 2.33 | 0 -- - > 2 var c = 2.33 > > 0 -- -- -- -- > 2Copy the code

6. Elegant formatting of money

1. Use re to implement vartest1 = '1234567890'
var format = test1.replace(/\B(? =(\d{3})+(? ! \d))/g,', 'Console. log(format) // 1,234,567,890function formatCash(str) {
       return str.split(' ').reverse().reduce((prev, next, index) => {
            return ((index % 3) ? next : (next + ', ') + prev})} console.log(format) // 1,234,567,890Copy the code

7. Five ways to exchange values

1. var temp = a; a = b; b = temp; (traditional, but with temporary variables) 2. b ^= a; a ^= b; (need two integer) (3) b = (a, a = b) [0] (with the help of an array) 4. [a, b] = [b, a]; 5. A = a + b; b = a - b; a = a - b; (Primary Olympiad questions)Copy the code

8. Implement deep copy

var b = JSON.parse(JSON.string(a))
Copy the code

9. Remove the decimal part

/ / the following several ways will do parseInt (num) ~ ~ num num > > 0 num | 0Copy the code

10. Recursively take a factorial


function factorial(n) {
 
  return (n > 1) ? n * f(n - 1) : n
 
Copy the code

11. Try printing

console.log(([][[]] + [])[+!![]] + ([] + {})[!+[] + !![]]) console.log((! (~ + []) + {}) [- [~ +' '[+[]] * [~+[]] + ~~! +[] + ({} +[])[[~!+[]] * ~+[]])Copy the code

12. The console beautification

console.info("% c ha ha"."color: #3190e8; font-size: 30px; font-family: sans-serif");
Copy the code

The last

  • If you are interested in this article, please like and follow