数组
4.1 用字面语法来创建数组
eslint:no-array-constructor
// bad
const items=new Array()
// good
const items=[]
4.2 使用Array.push而不是直接赋值来给数组添加元素
//bad
someStack([someStack.length])='fdsafdsf'
//good
someStack.push('fdsafgdsf')
4.3 用数组的扩展运算符...
来复制数组
// bad
const len=items.length
const itemsCopy=[]
let i
for(i=0;i<len;i+=1){
itemsCopy[i]=items[i]
}
// good
const itemsCopy=[...items]
4.4 如果要讲一个类数组对象转换成数组,使用扩展运算符...
代替Array.from
const foo=document.querySelectorAll('.foo')
//good
const nodes=Array.from(foo)
//best
const nodes=[...foo]
4.5 用Array.from而不是扩展运算符...
来映射迭代器,因为这样避免了创建中间数组
//bad
const baz=[...foo].map(bar)
//good
const baz=Array.from(foo,bar)
4.6 在数组的回调函数里使用return声明。如果函数体包含了一个单一声明,这样的话返回的是一个没有副作用的表达式,此时可以省去return
eslint:array-callback-return
// good
[1, 2, 3].map((x) => {
const y = x + 1;
return x * y;
});
// good
[1, 2, 3].map(x => x + 1);
// bad - no returned value means `memo` becomes undefined after the first iteration
[[0, 1], [2, 3], [4, 5]].reduce((memo, item, index) => {
const flatten = memo.concat(item);
memo[index] = flatten;
});
// good
[[0, 1], [2, 3], [4, 5]].reduce((memo, item, index) => {
const flatten = memo.concat(item);
memo[index] = flatten;
return flatten;
});
// bad
inbox.filter((msg) => {
const { subject, author } = msg;
if (subject === 'Mockingbird') {
return author === 'Harper Lee';
} else {
return false;
}
});
// good
inbox.filter((msg) => {
const { subject, author } = msg;
if (subject === 'Mockingbird') {
return author === 'Harper Lee';
}
return false;
});
4.7 如果一个数组有多行,则在打开和关闭数组的括号前面使用换行符
// bad
const arr = [
[0, 1], [2, 3], [4, 5],
];
const objectInArray = [{
id: 1,
}, {
id: 2,
}];
const numberInArray = [
1, 2,
];
// good
const arr = [[0, 1], [2, 3], [4, 5]];
const objectInArray = [
{
id: 1,
},
{
id: 2,
},
];
const numberInArray = [
1,
2,
];