codecamp

6. 字符串

  • 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}?`;
      }
5. 解构
7. 函数
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }