6. 字符串

2018-02-24 16:11 更新
  • 6.1?字符串使用單引號?''?。

    // bad
    const name = "Capt. Janeway";
    
    // good
    const name = 'Capt. Janeway';
  • 6.2?字符串超過 80 個字節(jié)應(yīng)該使用字符串連接號換行。

  • 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}?`;
      }
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號