Master 20 practical skills in JS development in 3 minutes

Time:2020-11-12

This article starts in Nuggets: Address: 3 minutes to master 20 practical tips in JS development

preface

Daily development, we may need to write a lot of JS code, the following development tips can help you. Words not much, directly on the code!

String technique

Format the thousandth

'10000000.00'.replace(/(?!^)(?=(\d{3})+\.)/g, ',');      // "10,000,000.00"
'10000000.00'.replace(/\B(?=(\d{3})+\.)/g, ',');        // "10,000,000.00"
'10000000.00'.replace(/\d{1,3}(?=(\d{3})+\.)/g, '$&,'); // "10,000,000.00"

0 digits in front of the date

let date1 = '2020-01-01 08:34:59'
let date2 = '2020-04-01 18:34:59'
data2 > date1 // true

Zero filling

const addZero1 = (num, len = 2) => `0${num}`.slice(-len)
addZero1(3) // 03
const addZero2 = (num, len = 2) => `${num}`.padStart(len, 0)
addZero2(5) // 05
Here we need to pay attention to the difference between the two usages: method one intercepts a fixed length, method two exceeds the specified length, and directly returns the original value

Numerical techniques

time stamp

const timestamp = +new Date('2020-02-02')  // timestamp => 1580601600000

Exact decimal places

const roundNum = (num, decimal) => Math.round(num * 10 ** decimal) / 10 ** decimal
roundNum(1.768, 2)  // 1.77

Judge parity

const a = 5
!!(a & 1)  // true
!!(a % 2)  // true

Rounding: a positive number is equal toMath.floor()Negative numbers are equivalent toMath.ceil()

const a1 = ~~1.333    // 1
Math.floor(1.333)     // 1

const a2 = ~~-1.333   // -1
Math.ceil(-1.333)       // -1    

const b1 = 1.333 | 0  // 1
const b2 = -1.333 | 0 // -1

const c1 = 1.333 >> 0 // 1
const c2 = -1.333 >> 0 // -1

Base conversion

num.toString (n) // decimal = > N base 
(13).toString(12)  // 11
ParseInt (Num, n) // N base = > decimal
parseInt(12, 8)       // 12
  • It can be expanded n (2 ~ 36) times without addition, subtraction, multiplication and division

    const convertN = (num, n) => parseInt(`${num.toString(n)}0`, n)
    convertN(12, 7) // 84

Array technique

Filter all the false values in the array. The false values in JS arefalsenullundefinedEmpty character0andNaN

const filterArr = arr => arr.filter(Boolean)
filterArr([1, false, null, undefined, '', NaN])   // [1]

Array summation

const arr = [1, 2, 3, 4];
arr.reduce((total, v) => total + v) // 10

Array max min

Math.min(...[1, 2, 3, 4]) // 1
Math.max(...[1, 2, 3, 4]) // 4

Data flattening

const flatten = (arr, n = 1) => 
    n > 0 
    ? arr.reduce((a, v) => a.concat(Array.isArray(v) ? flatten(v, n - 1) : v), [] )
    : arr

flatten([1, 2, [1, [3]], [4]]) // [1, 2, 1, Array(1), 4]
flatten([1, 2, [1, [3]], [4]], 2) // [1, 2, 1, 3, 4]

Exchange assignment

let a = 1;
let b = 2;
[a, b] = [b, a]
// a => 2, b => 1
  • Other implementation methods

    1、var temp = a; b = a; a = temp;
    2、b = [a, a = b][0]
    3、a = a + b; b = a - b; a = a - b;
    4、a ^= b; b ^= a; a ^= b;

Count the number of array members

const arr = [0, 2, 3, 2, null, ''];
const obj = arr.reduce((t, v) => {
    t[v] = t[v] ? ++ t[v] : 1;
    return t;
}, {});
// obj => {0: 1, 2: 2, 3: 1, null: 1, "": 1}

Creates an array of the specified length and each item is the same

new Array(5).fill(true) // [true, true, true, true, true]

Asynchronous accumulation

async function fn(arr) {
    return arr.reduce(async(t, v) => {
        const dep = await t;
        const res = await fn2(v);
        obj[v] = res;
        return obj;
    }, Promise.resolve({}));
}

const result = await fn();

Array de duplication

const arr = [...new Set([0, 1, 1, null, '', '',,])];  
// arr => [0, 1, null, "", undefined]

URL parameter splicing

const obj = { a: 1, b: 2 }
Object.entries(obj).map(param => param.join('=')).join('&') // "a=1&b=2"
Object.keys(obj).map(key => `${key}=${obj[key]}`).join('&') // "a=1&b=2"

Object technique

Structure to extract the required attributes

const { a, ...b } = { a: 1, b: 2, c: 3 }
// a => 1, b => { b: 2, c: 3 }

summary

The above are basically the tips often used in the development. If there is any omission, I will update it in time. At the same time, I hope you can comment or supplement below. You can enjoy itLike itorCollect itMaybe one day.