Flexible use of JS development skills

Joway Young

directory

  • String Skill:String techniques
  • Number Skill:Numerical techniques
  • Boolean Skill:Boolean skills
  • Array Skill:An array of skills
  • Object Skill:Object skills
  • Function Skill:Function skills
  • DOM Skill:DOM skills

Introduction to ES6 Standards

String Skill

Compare the time

The time single-digit form requires a complement of 0

const time1 = "The 2019-02-14 21:00:00";
const time2 = "The 2019-05-01 09:00:00";
const overtime = time1 > time2;
// overtime => false
Copy the code

Format money

const ThousandNum = num= > num.toString().replace(/\B(? =(\d{3})+(? ! \d))/g.",");
const money = ThousandNum(20190214);
// money => "20,190,214"
Copy the code

Generate random IDS

const RandomId = len= > Math.random().toString(36).substr(3, len);
const id = RandomId(10);
// id => "jg7zpgiqva"
Copy the code

Generates random HEX color values

const RandomColor = () = > "#" + Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6."0");
const color = RandomColor();
// color => "#f03665"
Copy the code

Generate star ratings

const StartScore = rate= > Painted "u u u u being fostered fostered fostered fostered".slice(5 - rate, 10 - rate);
const start = StartScore(3);
Painted painted / / start = > "u"
Copy the code

Manipulate URL query parameters

const params = new URLSearchParams(location.search.replace(/ \? /ig."")); // location.search = "? name=young&sex=male"
params.has("young"); // true
params.get("sex"); // "male"
Copy the code

Number Skill

integer

Math.floor() for positive numbers, math.ceil () for negative numbers

const num1 = ~~ 1.69;
const num2 = 1.69 | 0;
const num3 = 1.69 >> 0;
// num1 num2 num3 => 1 1 1
Copy the code

Zero padding

const FillZero = (num, len) = > num.toString().padStart(len, "0");
const num = FillZero(169.5);
// num => "00169"
Copy the code

Turn the numerical

This parameter is valid only for null, “”, false, and numeric strings

const num1 = +null;
const num2 = +"";
const num3 = +false;
const num4 = +"169";
// num1 num2 num3 num4 => 0 0 0 169
Copy the code

The time stamp

const timestamp = +new Date("2019-02-14");
// timestamp => 1550102400000
Copy the code

Precise decimal

const RoundNum = (num, decimal) = > Math.round(num * 10 ** decimal) / 10 ** decimal;
const num = RoundNum(1.69.1);
/ / num = > 1.7
Copy the code

Judge parity

const RoundNum = (num, decimal) = > Math.round(num * 10 ** decimal) / 10 ** decimal;
const num = RoundNum(1.69.1);
/ / num = > 1.7
Copy the code

Take the minimum maximum

const arr = [0.1.2];
const min = Math.min(... arr);const max = Math.max(... arr);// min max => 0 2
Copy the code

Generate range random number

const RandomNum = (min, max) = > Math.floor(Math.random() * (max - min + 1)) + min;
const num = RandomNum(1.10);
Copy the code

Boolean Skill

Short circuit calculation

const a = d && 1; // If the condition is met, the last true value is returned, and the false value is returned from left to right
const b = d || 1; // Default assignment: true operation, judging from left to right, return true value when encountered, no further execution, otherwise return the last false value
constc = ! d;// False assignment: returns false if a single expression is converted to true, or true otherwise
Copy the code

Determine the data type

Identifiable type: Undefined, NULL, string, Number, Boolean, array, object, symbol, date, RegEXP, function, AsyncFunction, arguments, set, map, WeakSet, we akmapCopy the code
function DataType(tgt, type) {
    const dataType = Object.prototype.toString.call(tgt).replace(/\[object (\w+)\]/."$1").toLowerCase();
    return type ? dataType === type : dataType;
}
DataType("young"); // "string"
DataType(20190214); // "number"
DataType(true); // "boolean"
DataType([], "array"); // true
DataType({}, "array"); // false
Copy the code

Whether the array is empty

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

Whether the object is empty

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

The command is executed when the conditions are met

const flagA = true; A / / conditions
const flagB = false; B / / conditions
(flagA || flagB) && Func(); // Execute when A or B is met(flagA || ! flagB) && Func();// Execute if A is met or B is not met
flagA && flagB && Func(); // Execute when both A and B are metflagA && ! flagB && Func();// Execute the command if A is met but B is not met
Copy the code

Executed when it is a non-false value

const flag = false; // undefined, null, "", 0, false, NaN! flag && Func();Copy the code

Execute when the array is not empty

const arr = [0.1.2];
arr.length && Func();
Copy the code

Executed when the object is not null

const obj = { a: 0.b: 1.c: 2 };
Object.keys(obj).length && Func();
Copy the code

Function exit replaces conditional branch exit

if (flag) {
    Func();
    return false;
}
/ / for
if (flag) {
    return Func();
}
Copy the code

Switch /case Usage range

const age = 26;
switch (true) {
    case isNaN(age):
        console.log("not a number");
        break;
    case (age < 18) :console.log("under age");
        break;
    case (age >= 18) :console.log("adult");
        break;
    default:
        console.log("please set your age");
        break;
}
Copy the code

Array Skill

Cloned array

const _arr = [0.1.2];
const arr = [..._arr];
// arr => [0, 1, 2]
Copy the code

Merge array

const arr1 = [0.1.2];
const arr2 = [3.4.5];
const arr = [...arr1, ...arr2];
// arr => [0, 1, 2, 3, 4, 5];
Copy the code

To weight array

const arr = [...new Set([0.1.1.null.null])];
// arr => [0, 1, null]
Copy the code

Confusing array

const arr = [0.1.2.3.4.5].slice().sort(() = > Math.random() - . 5);
// arr => [3, 4, 0, 5, 1, 2]
Copy the code

Empty array

const arr = [0.1.2];
arr.length = 0;
// arr => []
Copy the code

Truncation array

const arr = [0.1.2]
arr.length = 2;
// arr => [0, 1]
Copy the code

Exchange of assignment

let a = 0;
let b = 1;
[a, b] = [b, a];
// ab => 1 0
Copy the code

Filter the null

Null: undefined, null, “”, 0, false, NaN

const arr = [undefined.null."".0.false.NaN.1.2].filter(Boolean);
// arr => [1, 2]
Copy the code

Asynchronous cumulative

async function Func(deps) {
    return deps.reduce(async(t, v) => {
        const dep = await t;
        const version = await Todo(v);
        dep[v] = version;
        return dep
    }, Promise.resolve({}));
}

const result = await Func(); // Need to be used around async
Copy the code

Insert a member at the head of the array

let arr = [1.2]; // Choose one of the following methods
arr.unshift(0);
arr = [0].concat(arr);
arr = [0. arr];// arr => [0, 1, 2]
Copy the code

Insert a member at the end of an array

let arr = [0.1]; // Choose one of the following methods
arr.push(2);
arr.concat(2);
arr[arr.length] = 2;
arr = [...arr, 2];
// arr => [0, 1, 2]
Copy the code

Statistics the number of members in a group

const arr = [0.1.1.2.2.2];
const count = arr.reduce((t, v) = > {
    t[v] = t[v] ? ++[v] : 1;
    returnt; }, {});// count => { 0: 1, 1: 2, 2: 3 }
Copy the code

Deconstruct array member nesting

const arr = [0.1[2.3[4.5]]];
const [a, b, [c, d, [e, f]]] = arr;
// a b c d e f => 0 1 2 3 4 5
Copy the code

Structure array member alias

const arr = [0.1.2];
const { 0: a, 1: b, 2: c } = arr
// a b c => 0 1 2
Copy the code

Struct array member default value

const arr = [0.1.2];
const [a, b, c = 3, d = 4] = arr;
// a b c d => 0 1 2 4
Copy the code

Gets a random number member

const arr = [1.2.3.4.5];
const randomItem = arr[Math.floor(Math.random() * arr.length)];
// randomItem => 1
Copy the code

Creates an array of the specified length

const arr = [...new Array(3).keys()];
// arr => [0, 1, 2]
Copy the code

Creates an array of the specified length and equal values

const arr = new Array(3).fill(0);
// arr => [0, 0, 0]
Copy the code

Reduce replaces Map and Filter

const _arr = [0.1.2];

// map
const arr = _arr.map(v= > v * 2);
const arr = _arr.reduce((t, v) = > {
    t.push(v * 2);
    returnt; } []);// arr => [0, 2, 4]

// filter
const arr = _arr.filter(v= > v > 0);
const arr = _arr.reduce((t, v) = > {
    v > 0 && t.push(v);
    returnt; } []);// arr => [1, 2]

/ / map and filter
const arr = _arr.map(v= > v * 2).filter(v= > v > 2);
const arr = _arr.reduce((t, v) = > {
    v = v * 2;
    v > 2 && t.push(v);
    returnt; } []);// arr => [4]
Copy the code

Object Skill

Clone object

const _obj = { a: 0.b: 1.c: 2 };
constobj = { ... _obj };const obj = JSON.parse(JSON.stringify(_obj));
// obj => { a: 0, b: 1, c: 2 }
Copy the code

Merge objects

const obj1 = { a: 0.b: 1.c: 2 };
const obj2 = { c: 3.d: 4.e: 5 };
constobj = { ... obj1, ... obj2 };// obj => { a: 0, b: 1, c: 3, d: 4, e: 5 }
Copy the code

Object literals

Always use this method to get environment variables, always use it straight, always use it straight

const env = "prod";
const link = {
    dev: "Development Address".test: "Testing Address".prod: "Production Address"
}[env];

// link => "Production Address"
Copy the code

Object variable properties

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

Create a pure empty object

const obj = Object.create(null);
Object.prototype.a = 0;
// obj => {}
Copy the code

Delete unwanted attributes of an object

const obj = { a: 0.b: 1.c: 2 }; // Just want to get b and C
const{ a, ... rest } = obj;// rest => { b: 1, c: 2 }
Copy the code

Deconstruct object property nesting

const obj = { a: 0.b: 1.c: { d: 2.e: 3}};const { c: { d, e } } = obj;
// d e => 2 3
Copy the code

Deconstruct the object property alias

const obj = { a: 0.b: 1.c: 2 };
const { a, b: d, c: e } = obj;
// a d e => 0 1 2
Copy the code

Destruct object property defaults

const obj = { a: 0.b: 1.c: 2 };
const { a, b = 2, d = 3} = obj;
// a b d => 0 1 3
Copy the code

Function Skill

Function self-execution

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

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

Return value of an implicit function

Can only be used with single-statement return value arrow functions, if the return value is the object must be wrapped with ()

const Func = function(name) {
    return "I Love " + name
}

/ / for
const Func = name= > "I Love " + name;
Copy the code

One-time function

Good for running initialization code that only needs to be executed once

function Func() {
    console.log("x")
    Func = function() {
        console.log("y")}}Copy the code

Lazy loading function

When there are more and more complex judgment branches in the function, the resource cost can be greatly saved

function Func() {
    if (a === b){
        console.log("x");
    }else {
        console.log("Y"); }}/ / for
function Func() {
    if(a === b) {
        Func = function() {
            console.log("x")}}else {
        Func = function() {
            console.log("y")}}return Func();
}
Copy the code

Detects non-null parameters

function IsRequired() {
    throw new Error("param is required");
}
function Func(name = IsRequired()) {
    console.log("I Love" + name)
}
Func(); // "param is required"
Func("You") // "I Love You"
Copy the code

String creation function

const Func = new Function("name"."console.log(\"I Love \" + name)");
Copy the code

Handle error messages gracefully

try {
    Func();
} catch (e) {
    location.href = "https://stackoverflow.com/search?q=[js]+" + e.message;
}
Copy the code

Gracefully handle Async/ Await parameters

function AsyncTo(promise) {
    return promise.then(data= > [null, data]).catch(err= > [err]);
}
const [err, res] = await AsyncTo(Func());
Copy the code

Gracefully handle multiple function return values

function Func() {
    return Promise.all([
        fetch("/user"),
        fetch("/comment")])}const [user, comment] = await Func(); // It needs to be used with async surrounding
Copy the code

DOM Skill

Display all DOM borders

Used when debugging page element boundaries

[].forEach.call($$("*"), dom= > {
    dom.style.outline = "1px solid #"+ (~ ~ (Math.random() * (1 << 24))).toString(16);
});
Copy the code

Adaptive page

The page is based on a design drawing but needs to be adapted to multiple models. The element size is set by REM

function AutoResponse(width = 750) {
    const target = document.documentElement;
    target.clientWidth >= 600
        ? (target.style.fontSize = "80px")
        : (target.style.fontSize = target.clientWidth / width * 100 + "px");
}
Copy the code

Filtering XSS

function FilterXss(content) {
    let elem = document.createElement("div");
    elem.innerText = content;
    const result = elem.innerHTML;
    elem = null;
    return result;
}
Copy the code

Access the LocalStorage

Deserialize take, serialize store

localStorage.setItem("love".JSON.stringify("I Love You"));
const love = JSON.parse(localStorage.getItem("love"));
Copy the code

The keyboard

(_= >[..."`1234567890-=~~QWERTYUIOP[]\\~ASDFGHJKL; '~~ZXCVBNM,./~"].map(x= >(o+=` /${b='_'.repeat(w=x<y?2:'667699'[x=["Bs"."Tab"."Caps"."Enter"][p++]||'Shift',p])}\ \ | `,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