unicorn/no-useless-spread 正確性
作用
禁止在以下不必要的狀況使用展開語法
- 將陣列字面值展開為陣列字面值的元素
- 將陣列字面值展開為呼叫或
new
呼叫的參數 - 將物件字面值展開為物件字面值的屬性
- 使用展開語法複製內嵌建立的陣列
為何這樣不好?
以下內建函數接受可迭代物件,因此不需要將可迭代物件轉換為陣列
Map
建構函數WeakMap
建構函數Set
建構函數WeakSet
建構函數TypedArray
建構函數Array.from(…)
TypedArray.from(…)
Promise.{all,allSettled,any,race}(…)
Object.fromEntries(…)
for…of
迴圈可以迭代任何可迭代物件,而不僅僅是陣列,因此不需要將可迭代物件轉換為陣列。yield*
可以委派給另一個可迭代物件,因此不需要將可迭代物件轉換為陣列。
範例
javascript
const array = [firstElement, ...[secondElement], thirdElement];
const object = { firstProperty, ...{ secondProperty }, thirdProperty };
foo(firstArgument, ...[secondArgument], thirdArgument);
const object = new Foo(firstArgument, ...[secondArgument], thirdArgument);
const set = new Set([...iterable]);
async function foo() {
const results = await Promise.all([...iterable]);
}
for (const foo of [...set]);
function* foo() {
yield* [...anotherGenerator()];
}
function foo(bar) {
return [...bar.map((x) => x * 2)];
}
// Pass
const array = [firstElement, secondElement, thirdElement];
const object = { firstProperty, secondProperty, thirdProperty };
foo(firstArgument, secondArgument, thirdArgument);
const object = new Foo(firstArgument, secondArgument, thirdArgument);
const array = [...foo, bar];
const object = { ...foo, bar };
foo(foo, ...bar);
const object = new Foo(...foo, bar);
const set = new Set(iterable);
async function foo() {
const results = await Promise.all(iterable);
}
for (const foo of set);
function* foo() {
yield* anotherGenerator();
}
function foo(bar) {
return bar.map((x) => x * 2);
}