字符串

6.1 字符串使用单引号表示

eslint: quotes jscs: validateQuoteMarks

// bad
const name="Capt. Janeway"

// bad -模板文字应该包含插值或者换行符
const name = `Capt. Janeway`

// good 
const name = 'Capt. Janeway'

6.2 一行超过100个字符的字符串不应该用字符串连接写成多行

为什么?断开的字符串很难处理,而且也会很难被搜索到

// 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 template-curly-spacing jscs: requireTemplateStrings

为什么?模板字符串因为它正确的换行符和字符串插值有着很好地可读性和简洁的语法

// 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

6.5 不要去非必要的转义字符串中的字符

eslint: no-useless-escape

为什么?反斜杠会损害可读性,因此只有需要的时候才去用它们

// bad
const foo = '\'this\' \i\s \"quoted\"';

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

results matching ""

    No results matching ""