current position:Home>Summary of 17 JavaScript development skills

Summary of 17 JavaScript development skills

2021-08-27 02:06:31 Sexy little fat cat

This is my participation 8 The fourth of the yuegengwen challenge 23 God , Check out the activity details :8 Yuegengwen challenge

async/await

//  Standard usage :
function testAwait (x) {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve(x);
        }, 2000);
    });
}

async function helloAsync() {
var x = await testAwait ("hello world");
console.log(x);

//  perhaps :
// var x = testAwait ("hello world");// here x It's a Promise object 
// x.then(function(value){
// console.log(value);
// });
}
helloAsync ();
 Copy code 

Loose is equal ==

[ ] == [ ] // false 2 3  analysis : Two reference types ,== The comparison is the reference address 
 Copy code 

== and ! priority

[ ] == ![ ] // true

/*  analysis : (1)!  Has a higher priority than == , On the right Boolean([]) yes true, Return equals  false (2) A reference type and a value to compare   Convert reference types to value types , On the left 0 (3) therefore  0 == false  The answer is true */
 Copy code 

Numbers are added and subtracted from strings

'5' + 3
'5' - 3
//  analysis : The plus sign has splicing function , The minus sign is a logical operation 
//  To consolidate :typeof (+"1") // "number"  For non values +— It is often used for type conversion, which is equivalent to Number()
 Copy code 

Zero compensation

var FillZero = (num, len) => num.toString().padStart(len, "0");
var num = FillZero(156, 5);  // FillZero( Numbers ,  digit )
// num => "00156"
 Copy code 

Is an empty array

var arr = [];
var flag = Array.isArray(arr) && !arr.length;
// flag => true
 Copy code 

Whether it is an empty object

var obj = {};
var flag = DataType(obj, "object") && !Object.keys(obj).length;  // Object.keys(data).length !== 0
// flag => true
 Copy code 

Array comparison size

var a = [1, 2, 3],
b = [1, 2, 3],
c = [1, 2, 4];

a == b
a === b
a > c
a < c

/*  answer :false, false, false, true  analysis : equal (==) And all (===) It's still a reference address   The comparison size between reference types is in dictionary order , Who is bigger than the first item first , Compare the second item with the same one . */
 Copy code 

String.fromCharCode()

Method returns a value based on the specified UTF-16 A string created by a sequence of code units

let letterArr = []
//  elect 26 Letters 
for (let i = 65; i < 91; i++) {
    letterArr.push(String.fromCharCode(i))
}
letterArr = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
 Copy code 

Array weight removal

var arr = [...new Set([0, 2, 2, null, null])];
// arr => [0, 2, null]
 Copy code 

if Multi condition judgment

I don't think this is easy to use , The code looks much more comfortable .

//  redundancy 
if (x === 'a' || x === 'b' || x === 'c' || x ==='d') {
    // something 
}

//  concise 
//  The return is a Boolean value 
if (['a', 'b', 'c', 'd'].includes(x)) {
    // something 
}
 Copy code 

Optimize if else,switch

let code; // code There are multiple values  1 2 3 4 5,  Do different things separately 

//  common  if  How to write it ,  It looks dense , It makes people's scalp numb 
if (code === 1) {
  TodoA();
} else if (code === 2) {
  TodoB();
} else if (code === 3) {
  TodoC();
} else if (code === 4) {
  TodoD();
} else if (code === 5) {
  TodoE();
}

// switch  Optimize it ,  Such code itself is nothing , It's just less readable , It seems a little hard 
switch (code) {
  case 1:
    TodoA();
    break;
  case 2:
    TodoB();
    break;
  case 3:
    TodoC();
    break;
  case 4:
    TodoD();
    break;
  case 5:
    TodoE();
    break;

  default:
    break;
}

//  Last, last , Skillfully use objects to “ grace ” Solve this long string of code 
const codeNum = {
  1: TodoA,
  2: TodoB,
  3: TodoC,
  4: TodoD,
  5: TodoE,
}
if (codeNum[code]) {
  codeNum[code]();
}

//  Look at the code , Don't be too concise , You can lie down and fish again 
 Copy code 

find

Method returns the value of the first element in the array that satisfies the provided test function . Otherwise return to  undefined.

grammar :array.find(mapfuc)

let array = [0,12,22,55,44]
console.log(array.find((item,index) => item >= 18)) // 22
 Copy code 

Early exit mechanism

I believe you have seen such a code

function test(form) {
    if (form) {
        let flag = form.status;
        if (flag) {
            // something code
        }
    }
}
 Copy code 

When the value required by a condition is below a certain value , We have to make two judgments

Let's write it another way

function test(form) {
    if (!form && !form.status) {
        return;
    }
    // something code
}
 Copy code 

Everybody knows , And operator (&) Only when Both are true Only when true, Then if if This statement is false , The program doesn't execute any other code .

Object variable properties

What does that mean ? The red book explains this Computable properties Of : Before introducing computable properties , If you want to use the value of a variable as an attribute , Then you have to declare the object first , Then use the bracket syntax to add properties . let me put it another way , You can't name properties dynamically directly in the literal of an object .

image.png

var flag = false;
var obj = {
    a: 0,
    b: 1,
    [flag ? "c" : "d"]: 2
};
// obj => { a: 0, b: 1, d: 2 }
 Copy code 

For this writing , I also have for axios in ,

For dynamic control axios Of params(get request ),data(post request ) ---------  Object key values can use [ Variable or expression ]

let method = plat == 'xxx' ? 'get' : 'post';  //  When  plat Equal to a certain value is get request , Otherwise post request 

axios({
  method, //  Request mode 
  [ method == 'get' ? 'params' : 'data' ]: data //  Object key values can use  [  Variable or expression  ] data Is the data returned to the back end 
}).then(() => {}).catch(() => {})
 Copy code 

Function exit replaces conditional branch exit

if (flag) {
    Func();
    return false;
}

//  Switch to 
if (flag) {
    return Func();
}
 Copy code 

Format money

let formatMoney = num => num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
let money = formatMoney(986542135);
console.log('money ==> ', money);  // ""986,542,135""
 Copy code 

copyright notice
author[Sexy little fat cat],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210827020628800o.html

Random recommended