zoukankan      html  css  js  c++  java
  • 养成一些好的代码习惯

    1.不要污染函数作用域

    if 块作用域
    // 不好
    let message;
    // ...
    if (notFound) {
      message = 'Item not found';
      // Use `message`
    }
    
    // 好
    if (notFound) {
      const message = 'Item not found';
      // Use `message`
    }
    
    for 块作用域
    // 不好
    let item;
    for (item of array) {
      // Use `item`
    }
    
    // 好
    for (const item of array) {
      // Use `item`
    }
    }
    

    2.尽量避免 undefined 和 null

    判断属性是否存在
    // 不好
    const object = {
      prop: 'value'
    };
    if (object.nonExistingProp === undefined) {
      // ...
    }
    
    // 好
    const object = {
      prop: 'value'
    };
    if ('nonExistingProp' in object) {
      // ...
    }
    
    对象的默认属性
    // 不好
    function foo(options) {
      if (object.optionalProp1 === undefined) {
        object.optionalProp1 = 'Default value 1';
      }
      // ...
    }
    
    // 好
    function foo(options) {
      const defaultProps = {
        optionalProp1: 'Default value 1'
      };
      options = {
        ...defaultProps,
        ...options
      }
    }
    
    默认函数参数
    // 不好
    function foo(param1, param2) {
      if (param2 === undefined) {
        param2 = 'Some default value';
      }
      // ...
    }
    // 好
    function foo(param1, param2 = 'Some default value') {
      // ...
    }
    

    3.不要使用隐式类型转换

  • 相关阅读:
    Mathematics:GCD & LCM Inverse(POJ 2429)
    MST:Out of Hay(POJ 2395)
    DP:Cow Exhibition(POJ 2184)(二维问题转01背包)
    《程序员修炼之道——从小工到专家》阅读笔记*part1
    Java课05
    Java课04
    Javaweb课堂测试
    Java课03
    Java课02
    回文判断
  • 原文地址:https://www.cnblogs.com/IT123/p/11302731.html
Copyright © 2011-2022 走看看