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ì)對性能造成影響。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}?`;
}
更多建議: