js代码简写优化

2021-03-02 10:13:26 浏览数 (1)

单个值进行多个if判断

代码语言:javascript复制
    let val = 1
    // old
    if (val == 1 || val == 2 || val == 3) { }
    // new
    if ([1, 2, 3].includes(val)) { }

for循环

代码语言:javascript复制
    var list = [1, 2, 3, 4]
    // old
    for (let i = 0; i < list.length; i  ) { }
    // new
    for (let i in list) { }

多个变量赋值

代码语言:javascript复制
    // old
    let a = 1;
    let b = 2;
    let c = 3;
    // new
    let [a, b, c] = [1, 2, 3];

||判断nullundefined""0false

代码语言:javascript复制
   var val = ""
    // old
    if (val != null && val != undefined && val != "" && val != 0 && val != false) { }
    // new
    val || "back"

??判断nullundefined

代码语言:javascript复制
    var val = ""
    // old
    if (val != null && val != undefined) { }
    // new
    val ?? "back"

String转换成number

代码语言:javascript复制
    // old
    let a = parseInt('100');
    let a = parseFloat('100.1');
    let a = Number('100')
    // new
    let a =  '100';

0 人点赞