前端冷门小技巧(持续更新^^)

211 阅读1分钟
  1. 非空非null非undefined判断

    let demo;

    demo !== 'null' && demo !=='undefined' && demo !==''

    使用??运算符

    如果不等于Null和undefined,取自身值,反之取??右侧值

    (demo??'') !== ''

  2. String类型数字转Number

    let demoOne = '12';

    let demoTwo = '34';

    Number(demoOne) + Number(demoTwo)

    使用一元运算符 +,一元运算符 + 优先级高于二元运算符 +

    +应用于单个值,对数字没用,但能将非数字值转换为数字,与Number相同,但更简洁

    +demoOne + +demoTwo

  3. 转换Boolean类型

    Boolean('Hello World')

    使用!运算符,第一个非运算符转换为布尔值取反,第二个布尔值再取反,就得到任意值到布尔值的转换

    !!'Hello World'

  4. break跳出多层for循环

        for (let i = 0; i < 3; i++) {
          for (let j = 0; j < 3; j++) {
            if (j === 2) break;
          }
          break;
        }
    

    使用标签可以实现这一功能 标签时循环前带有冒号的标识符

    break <标签名>会跳至标签处

        outer:for (let i = 0; i < 3; i++) {
          for (let j = 0; j < 3; j++) {
            if (j === 2) break outer;
          }
        }
    
  5. switch循环 case分组

        let demo = 3;
        switch (demo) {
            case 1:
                console.log('hello');
                break;
            case 3:
                console.log('world');
                break;
            case 5:
                console.log('world');
                break;
        }
    

    几个case分支可以分为一组,共享一段代码块

        let demo = 3;
        switch (demo) {
            case 1:
                console.log('hello');
                break;
            case 3:
            case 5:
                console.log('world');
                break;
        }
    

    因为没有break,case 3 行会执行到case 5 行

  6. axios 取消请求(cancelToken)

    axios实例传入axios.CancelToken.source()返回的对象 如果XHRAbort有值,就取消请求(XHRAbort.cancel())

    image.png

  7. 解决数字运算精度损失问题

    console.log(0.1 + 0.2 === 0.3); // false
    console.log(0.1 + 0.2); // 0.30000000000000004
    

    通过.toFixed()对结果进行舍入来解决

    console.log(+(0.1 + 0.2).toFixed(2)); // 0.3
    
  8. 对于要写很多0的数字

    let num = 100000000;
    

    将'e'和0的数量赋到数字后

    let positiveNum = 1e8;
    console.log(positiveNum); // 100000000
    
    let negativeNum = 1e-5;
    console.log(negativeNum); // 0.00001