# 字符串

  • 6.1 对string用单引号 '' 。 eslint: quotes (opens new window)

    // bad
    const name = "Capt. Janeway";
    
    // bad - 样例应该包含插入文字或换行
    const name = `Capt. Janeway`;
    
    // good
    const name = 'Capt. Janeway';
    
  • 6.2 超过 120 个字符的字符串不应该用string串联成多行。

    Why? 被折断的字符串工作起来是糟糕的而且使得代码更不易被搜索。

    // 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.3 用字符串模板而不是字符串拼接来组织可编程字符串。 eslint: prefer-template (opens new window) template-curly-spacing (opens new window)

    Why? 模板字符串更具可读性、语法简洁、字符串插入参数。

    // bad
    function sayHi(name) {
      return 'How are you, ' + name + '?';
    }
    
    // bad
    function sayHi(name) {
      return ['How are you, ', name, '?'].join();
    }
    
    // bad
    function sayHi(name) {
      return `How are you, ${ name }?`;
    }
    
    // good
    function sayHi(name) {
      return `How are you, ${name}?`;
    }
    
  • 6.4 永远不要在字符串中用eval(),他就是潘多拉盒子。 eslint: no-eval (opens new window)

  • 6.5 不要使用不必要的转义字符。eslint: no-useless-escape (opens new window)

    Why? 反斜线可读性差,所以他们只在必须使用时才出现哦

    // bad
    const foo = '\'this\' \i\s \"quoted\"';
    
    // good
    const foo = '\'this\' is "quoted"';
    
    //best
    const foo = `my name is '${name}'`;
    

回到顶部