zoukankan      html  css  js  c++  java
  • js优化小技巧

    1、含有多个条件的if语句

    我们可以在数组中存储多个值,并且可以使用数组的 includes 方法。

    //longhand
    if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {
        //logic
    }
    //shorthand
    if (['abc', 'def', 'ghi', 'jkl'].includes(x)) {
       //logic
    }

    2、对null、undefined、empty这些值的检查

    我们创建一个新变量,有时候需要检查是否为 Null 或 Undefined。JavaScript 本身就有一种缩写法能实现这种功能。

    // Longhand
    if (test1 !== null || test1 !== undefined || test1 !== '') {
        let test2 = test1;
    }
    // Shorthand
    let test2 = test1 || '';

    3、同时为多个变量赋值

    当我们处理多个变量,并且需要对这些变量赋不同的值,这种缩写法很有用。

    //Longhand 
    let test1, test2, test3;
    test1 = 1;
    test2 = 2;
    test3 = 3;
    //Shorthand 
    let [test1, test2, test3] = [1, 2, 3];

    4、隐式返回缩写法

    使用箭头函数,我们可以直接得到函数执行结果,不需要写 return 语句。

    //longhand
    function calculate(diameter) {
      return Math.PI * diameter
    }
    //shorthand
    calculate = diameter => (
      Math.PI * diameter;
    )

    5、十进制指数形式

    // Longhand
    for (var i = 0; i < 10000; i++) { ... }
    
    // Shorthand
    for (var i = 0; i < 1e4; i++) {

    6、查询条件缩写法

    如果我们要检查类型,并根据类型调用不同的函数,我们既可以使用多个 else if 语句,也可以使用 switch,除此之外,如果有缩写法,代码会是怎么样呢?

    // Longhand
    if (type === 'test1') {
      test1();
    }
    else if (type === 'test2') {
      test2();
    }
    else if (type === 'test3') {
      test3();
    }
    else if (type === 'test4') {
      test4();
    } else {
      throw new Error('Invalid value ' + type);
    }
    // Shorthand
    var types = {
      test1: test1,
      test2: test2,
      test3: test3,
      test4: test4
    };
     
    var func = types[type];
    (!func) && throw new Error('Invalid value ' + type); func();
  • 相关阅读:
    OGNL与值栈
    Struts2的数据封装
    Struts2页面配置和访问servlet API
    Struts2入门介绍(二)
    Struts2 入门介绍(一)
    Hibernate批量抓取
    Problem G: STL——整理唱片(list的使用)
    STL详细介绍(更新中~~~)
    Problem E: 数量的类模板
    CF: Long Number
  • 原文地址:https://www.cnblogs.com/ltog/p/14516216.html
Copyright © 2011-2022 走看看