首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

yoda

--fix命令行上的选项可以自动修复一些被这条规则反映的问题。

Yoda 条件是如此命名的,因为条件的字面值首先出现,而变量出现在第二位。例如,以下是 Yoda 条件:

if ("red" === color) {
    // ...
}

被称为 Yoda 条件的原因是它读作“如果红色等于颜色”,类似于星球大战角色 Yoda 所说的方式。与安排操作数的其他方式相比:

if (color === "red") {
    // ...
}

这通常表示“如果颜色等于红色”,这可以说是一种更自然的方式来描述比较。

Yoda 条件的支持者强调,不可能错误地使用,=而不是==因为你不能分配字面值。这样做会导致语法错误,并会在早期通知您错误。因此,这种做法在早期的编程工具中尚不可用的情况下非常普遍。

Yoda 条件的反对者指出,工具使我们更好的程序员,因为工具会抓住错误的使用,=而不是==(ESLint会为你着想)。因此,他们认为,模式的效用不会超过代码在使用 Yoda 条件时需要的可读性。

规则细节

这条规则旨在强制执行一种将变量与文字值进行比较的一致条件样式。

选项

此规则可以采用字符串选项:

  • 如果它是默认值"never",那么比较绝不能是 Yoda 条件。
  • 如果是"always",那么字面值必须始终在前。
  • 默认"never"选项可以在对象文字中具有异常选项:
  • If the "exceptRange" property is true, the rule allows yoda conditions in range comparisons which are wrapped directly in parentheses, including the parentheses of an if or while condition. The default value is false. A range comparison tests whether a variable is inside or outside the range between two literal values.
  • If the "onlyEquality" property is true, the rule reports yoda conditions only for the equality operators == and ===. The default value is false.

onlyEquality选项允许超出允许的例外exceptRange,因此这两个选项在一起不起作用。

决不

不正确的代码为默认"never"选项的示例:

/*eslint yoda: "error"*/

if ("red" === color) {
    // ...
}

if (true == flag) {
    // ...
}

if (5 > count) {
    // ...
}

if (-1 < str.indexOf(substr)) {
    // ...
}

if (0 <= x && x < 1) {
    // ...
}

默认选项的正确代码示例"never"

/*eslint yoda: "error"*/

if (5 & value) {
    // ...
}

if (value === "red") {
    // ...
}

exceptRange

"never", { "exceptRange": true }选项的正确代码示例:

/*eslint yoda: ["error", "never", { "exceptRange": true }]*/

function isReddish(color) {
    return (color.hue < 60 || 300 < color.hue);
}

if (x < -1 || 1 < x) {
    // ...
}

if (count < 10 && (0 <= rand && rand < 1)) {
    // ...
}

function howLong(arr) {
    return (0 <= arr.length && arr.length < 10) ? "short" : "long";
}

onlyEquality

"never", { "onlyEquality": true }选项的正确代码示例:

/*eslint yoda: ["error", "never", { "onlyEquality": true }]*/

if (x < -1 || 9 < x) {
}

if (x !== 'foo' && 'bar' != x) {
}

always

"always"选项的错误代码示例:

/*eslint yoda: ["error", "always"]*/

if (color == "blue") {
    // ...
}

"always"选项的正确代码示例:

/*eslint yoda: ["error", "always"]*/

if ("blue" == value) {
    // ...
}

if (-1 < str.indexOf(substr)) {
    // ...
}

进一步阅读

扫码关注腾讯云开发者

领取腾讯云代金券