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


使用剩余參數代替 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變量,你可以關閉它。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM