版本

no-var

要求使用 letconst 而非 var

🔧 可修正

此規則回報的一些問題可以透過 --fix 命令列 選項自動修正

ECMAScript 6 允許程式設計師使用 letconst 關鍵字建立區塊作用域變數,而不是函式作用域。區塊作用域在許多其他程式語言中很常見,並有助於程式設計師避免犯錯,例如

var count = people.length;
var enoughFood = count > sandwiches.length;

if (enoughFood) {
    var count = sandwiches.length; // accidentally overriding the count variable
    console.log("We have " + count + " sandwiches for everyone. Plenty for all!");
}

// our count variable is no longer accurate
console.log("We have " + count + " people and " + sandwiches.length + " sandwiches!");

規則詳細資訊

此規則旨在勸阻使用 var,並鼓勵改用 constlet

範例

此規則的不正確程式碼範例

在 Playground 中開啟
/*eslint no-var: "error"*/

var x = "y";
var CONFIG = {};

此規則的正確程式碼範例

在 Playground 中開啟
/*eslint no-var: "error"*/

let x = "y";
const CONFIG = {};

何時不該使用

除了非 ES6 環境之外,開始在其程式碼庫中引入 ES6 的現有 JavaScript 專案可能不想套用此規則,如果從 var 遷移到 let 的成本太高。

版本

此規則在 ESLint v0.12.0 中引入。

資源

變更語言