gihub连接: github.com/BingKui/jav…
1、使用对象方法的缩写。 eslint: object-shorthand
2、使用 Array#push 取代直接赋值来给数组添加项
3、如果数组有多行,则在开始的时候换行,然后在结束的时候换行。
4、在访问和使用对象或数组的多个属性的时候使用对象或数组的解构。 eslint: prefer-destructuring
解构可以避免属性创造临时引用
function getFullName({ firstName, lastName }) {
return `${firstName} ${lastName}`;
}
const arr = [1, 2, 3, 4];
// bad
const first = arr[0];
const second = arr[1];
// good
const [first, second] = arr;
5、对于多个返回值使用对象解构,而不是数组解构
// bad
function processInput(input) {
// 处理代码...
return [left, right, top, bottom];
}
// 调用者需要考虑返回数据的顺序。
const [left, __, top] = processInput(input);
// good
function processInput(input) {
// 处理代码...
return { left, right, top, bottom };
}
// 调用者只选择他们需要的数据。
const { left, top } = processInput(input);
6、使用命名的函数表达式代替函数声明
// bad
function foo() {
// ...
}
// bad
const foo = function () {
// ...
};
// good
// 从变量引用调用中区分的词汇名称
const short = function longUniqueMoreDescriptiveLexicalFoo() {
// ...
};
7、切记不要在非功能块中声明函数 (if, while, 等)。 将函数赋值给变量。 浏览器允许你这样做,但是他们都有不同的解释,这是个坏消息。
// bad
if (currentUser) {
function test() {
console.log('Nope.');
}
}
// good
let test;
if (currentUser) {
test = () => {
console.log('Yup.');
};
}
8、总是把默认参数放在最后
// bad
function handleThings(opts = {}, name) {
// ...
}
// good
function handleThings(name, opts = {}) {
// ...
}
9、没用变异参数。 eslint: no-param-reassign
为什么? 将传入的对象作为参数进行操作可能会在原始调用程序中造成不必要的变量副作用。
// bad
function f1(obj) {
obj.key = 1;
}
// good
function f2(obj) {
const key = Object.prototype.hasOwnProperty.call(obj, 'key') ? obj.key : 1;
}
10、如果函数体包含一个单独的语句,返回一个没有副作用的 expression , 省略括号并使用隐式返回。否则,保留括号并使用 return 语句。 eslint: arrow-parens, arrow-body-style
11、 方法返回了 this 来供其内部方法调用。
12、 只从一个路径导入所有需要的东西
// good
import foo, {
named1,
named2,
} from 'foo';
13、在你需要的使用定义变量,但是要把它们放在一个合理的地方。 看原文;
14、对于布尔值使用简写,但是对于字符串和数字进行显式比较。
// bad
if (collection.length) {
// ...
}
// good
if (collection.length > 0) {
// ...
}
15、如果你的控制语句 (if, while 等) 太长或者超过了一行最大长度的限制,则可以将每个条件(或组)放入一个新的行。 逻辑运算符应该在行的开始。
// good
if (
(foo === 123 || bar === 'abc')
&& doesItLookGoodWhenItBecomesThatLong()
&& isThisReallyHappening()
) {
thing1();
}
// good
if (foo === 123 && bar === 'abc') {
thing1();
}
16、在块和下一个语句之前留下一空白行
17、添加尾随逗号, 扩展符后面不能有逗号。
// good (注意逗号不能出现在 "rest" 元素后边)
createHero(
firstName,
lastName,
inventorOf,
...heroArgs
);
18、数字类型:使用 Number 进行类型铸造和 parseInt 总是通过一个基数来解析一个字符串。
// good
const val = parseInt(inputValue, 10);