JavaScript中的简写技巧

99 阅读1分钟
  • 给多个变量赋值

    let a, b, c;
    a = 5;
    b = 8;
    c = 10;
    ​
    let [a, b, c] = [5, 8, 10]
    
  • 与(&&)短路运算

    if (isLogin) {
        goHome();
    }
    ​
    isLogin && goHome();
    
  • 交换两个变量

    let x = 'hello', y = 66;
    const temp = x;
    x = y;
    y = temp;[x, y] = [y, x] 
    
  • 对象属性复制

     // 当对象的属性和值相同时,只需要在对象中声明变量名
     let firstname = 'Amitav';
     let lastname = 'Mishra';
     let obj = {firstname: firstname, lastname : lastname}
     
     let obj = {firstname, lastname}
    
  • 字符串转数字,重复一个字符串N次, 指数幂, ~~运算符

    // + 可以将字符串转为数字
    let a = 456;
    let b = 45.6
    let total = parseInt(a);
    let average = parseFloat(b)
    ​
    let total = +a;
    let average = +b;
    ​
    // 重复一个字符串N次 
    str.repeat(N)
    const power = Math.pow(4, 3);
    ​
    const power = 4**3;
    ​
    // 双非位运算符是Math.floor()方法的缩写
    const floor = Math.floor(6.8);
    const floor = ~~6.8;
    ​
    // 找出数组中的最大值和最小值
    const arr = [2, 8, 10, 20]
    Math.max(...arr)
    Math.min(...arr)
    ​
    ​
    
  • 合并数组

    let arr1 = [20, 30];
    let arr2 = arr1.concat([60, 80]);
    ​
    let arr = [...arr1, 60, 80]
    
  • 获取字符串中的字符

    let str = 'jscurious';
    str.charAt(2);
    ​
    str[2]
    

\