js代码简写优化

单个值进行多个if判断

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

for循环

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

多个变量赋值

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

||判断nullundefined""0false

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

??判断nullundefined

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

String转换成number

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

猜你喜欢

转载自blog.csdn.net/AK852369/article/details/113883713