版本

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 来代替。

示例

此规则的 错误 代码示例

在游乐场中打开
/*eslint no-var: "error"*/

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

此规则的 正确 代码示例

在游乐场中打开
/*eslint no-var: "error"*/

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

何时不使用

除了非 ES6 环境之外,如果从 var 迁移到 let 的成本太高,那么开始在其代码库中引入 ES6 的现有 JavaScript 项目可能不想应用此规则。

版本

此规则在 ESLint v0.12.0 中引入。

资源

更改语言