6. 字符串

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

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

  • 6.3?注:過度使用字串連接符號(hào)可能會(huì)對(duì)性能造成影響。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?程序化生成字符串時(shí),使用模板字符串代替字符串連接。

    為什么?模板字符串更為簡潔,更具可讀性。

      // 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)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)