使用剩餘參數代替 arguments (prefer-rest-params)

使用剩餘參數代替 arguments (prefer-rest-params)

剩餘參數來自於ES2016。能夠在可變函數中使用這個特性來替代arguments變量。
arguments沒有Array.prototype方法,因此使用起來有一點麻煩。app

詳細規則

這條規則旨在標記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變量,你能夠關閉它。prototype

相關文章
相關標籤/搜索