使用剩余參數代替 arguments
(prefer-rest-params)
剩余參數來自於ES2016。可以在可變函數中使用這個特性來替代arguments
變量。
arguments
沒有Array.prototype
方法,所以使用起來有一點麻煩。
詳細規則
這條規則旨在標記arguments
變量。
例子
- 不正確的例子
function foo() {
console.log(arguments);
}
function foo(action) {
var args = [].slice.call(arguments, 1);
action.apply(null, args);
}
- 正確的例子
function foo(...args) {
console.log(args);
}
function foo(action, ...args) {
action.apply(null, args); // or `action(...args)`, 參照 `prefer-spread`(展開操作規則).
}
// Note: 內建arguments變量可以被覆蓋
function foo(arguments) {
console.log(arguments); // 第一個參數.
}
function foo() {
var arguments = 0;
console.log(arguments); // 本地變量
}
什么時候不使用它
這條規則不能被用在ES3/5
的環境下。
在ES2015 (ES6)
或者之后的環境,如果不能被提醒arguments
變量,你可以關閉它。