Strings

  • 6.1 字符串使用单引号 ''

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

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

    1. // bad
    2. 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.';
    3. // bad
    4. const errorMessage = 'This is a super long error that was thrown because \
    5. of Batman. When you stop to think about how Batman had anything to do \
    6. with this, you would get nowhere \
    7. fast.';
    8. // good
    9. const errorMessage = 'This is a super long error that was thrown because ' +
    10. 'of Batman. When you stop to think about how Batman had anything to do ' +
    11. 'with this, you would get nowhere fast.';

  • 6.4 程序化生成字符串时,使用模板字符串代替字符串连接。

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

    1. // bad
    2. function sayHi(name) {
    3. return 'How are you, ' + name + '?';
    4. }
    5. // bad
    6. function sayHi(name) {
    7. return ['How are you, ', name, '?'].join();
    8. }
    9. // good
    10. function sayHi(name) {
    11. return `How are you, ${name}?`;
    12. }