js code shorthand optimization

Multiple ifjudgments for a single value

    let val = 1
    // old
    if (val == 1 || val == 2 || val == 3) {
    
     }
    // new
    if ([1, 2, 3].includes(val)) {
    
     }

forcycle

    var list = [1, 2, 3, 4]
    // old
    for (let i = 0; i < list.length; i++) {
    
     }
    // new
    for (let i in list) {
    
     }

Multiple variable assignment

    // old
    let a = 1;
    let b = 2;
    let c = 3;
    // new
    let [a, b, c] = [1, 2, 3];

||Determination null, undefined, "", 0,false

   var val = ""
    // old
    if (val != null && val != undefined && val != "" && val != 0 && val != false) {
    
     }
    // new
    val || "back"

??Judge null,undefined

    var val = null
    // old
    if (val != null && val != undefined) {
    
     }
    // new
    val ?? "back"

StringConvert tonumber

    // old
    let a = parseInt('100');
    let a = parseFloat('100.1');
    let a = Number('100')
    // new
    let a = +'100';

Guess you like

Origin blog.csdn.net/AK852369/article/details/113883713
Recommended