6. 字符串

2018-02-24 16:11 更新
  • 6.1 字符串使用单引号 '' 。

    // bad
    const name = "Capt. Janeway";
    
    // good
    const name = 'Capt. Janeway';
  • 6.2 字符串超过 80 个字节应该使用字符串连接号换行。

  • 6.3 注:过度使用字串连接符号可能会对性能造成影响。jsPerf 和 讨论.

    // bad
    const errorMessage = 'This is a super long error that was thrown because of Batman. When you stop to think about how Batman had anything to do with this, you would get nowhere fast.';
    
    // bad
    const errorMessage = 'This is a super long error that was thrown because \
    of Batman. When you stop to think about how Batman had anything to do \
    with this, you would get nowhere \
    fast.';
    
    // good
    const errorMessage = 'This is a super long error that was thrown because ' +
      'of Batman. When you stop to think about how Batman had anything to do ' +
      'with this, you would get nowhere fast.';
  • 6.4 程序化生成字符串时,使用模板字符串代替字符串连接。

    为什么?模板字符串更为简洁,更具可读性。

      // bad
      function sayHi(name) {
        return 'How are you, ' + name + '?';
      }
    
      // bad
      function sayHi(name) {
        return ['How are you, ', name, '?'].join();
      }
    
      // good
      function sayHi(name) {
        return `How are you, ${name}?`;
      }
以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号