no-return-assign
在 return
语句中不允许赋值运算符
JavaScript 的一个有趣且有时令人困惑的方面是赋值几乎可以在任何时候发生。因此,当真正的意图是进行比较时,错误的等号最终可能会导致赋值。在使用 return
语句时尤其如此。例如:
function doSomething() {
return foo = bar + 2;
}
在这里很难说出 return
声明的意图。该函数可能是为了返回 bar + 2
的结果,但为什么要分配给 foo
呢?也有可能是为了使用比较运算符,例如 ==
,并且此代码是错误的。
由于这种歧义,最好不要在 return
语句中使用赋值。
规则详情
该规则旨在消除 return
语句中的赋值。因此,只要发现分配是 return
的一部分,它就会发出警告。
选项
O/XgU19OKjlFjJqXM+T1dZQwtemvhmg5Ou8GXoMmKpkjfAmOBWmYMazn0w9ql8yc0gHd4da0Wx6kk+7puSBVqoH0vALswltztxOSzbcZ2a6j6sQdk4aQs7ewzONGyDfY
- KKwDfYVyHbSCn2fIJGBbiCBFJsRwPSmJ997Elk/O1ts0hL7rEvtoRae5UM1jqMs9ycdrKA4viebfF4Ay9kgodWZmEiUZAMXba1QEnX5UNUmNRLgYNwfltVLFHdibhsdyLL58GzL4pCaw6ufkzFDMMf9U+k/v8rFYoIRalS4jqG2cjDrK1C7CZXFjuKXkhUwZYgl3/qqA68c/aQzGDN3X9e8VKIlAlzqUSSCCjAxVNG8=
except-parens
qv+BgRfuJhNi7hOlI87fssDV8B4rYSWDY7rL+LEqTa83SAUJhqkR+DuDH8DL01fXTL46aW7vPdZSpYeHk2h8kggpfIS1dyhGgq7wb1UXLwg=
ufP5w3n2/ag+/LFLTKgnKnOcvy2LZpDO3laNtEP3qS+BKTaWHYVwq0WHmvWWSED2a75o0JmAZd4+c19rGAFEFSP8mXmpyqbXFj4lYTSEly8=
/*eslint no-return-assign: "error"*/
function doSomething() {
return foo = bar + 2;
}
function doSomething() {
return foo += 2;
}
const foo = (a, b) => a = b
const bar = (a, b, c) => (a = b, c == b)
function doSomething() {
return foo = bar && foo > 0;
}
ufP5w3n2/ag+/LFLTKgnKnOcvy2LZpDO3laNtEP3qS+WF/9tG5fH7uikIapIgGlWnZ1XSHjZXw0PUP+7jWiwpLQw/nfpoPJLoEyY6r3yKWI=
/*eslint no-return-assign: "error"*/
function doSomething() {
return foo == bar + 2;
}
function doSomething() {
return foo === bar + 2;
}
function doSomething() {
return (foo = bar + 2);
}
const foo = (a, b) => (a = b)
const bar = (a, b, c) => ((a = b), c == b)
function doSomething() {
return (foo = bar) && foo > 0;
}
always
Ldi0TJtQ72z8yNw2or2cfpnjW4PYiHzmAGnM0oC5mqcP6CNdbQIsm7XeDPLiAgBkFt/jcDAZ7wAqcVPksgp6BVpD04hTAJmrhTOyNW4drdVbpGHRxAlohKtiA+vtw7iWzfQnxrAboPE02MVBtJXJVA==
c8bJzypGHof5srMaCIwW3S47R2sh70aM8jjiYsJ56NMcj7E7mGq4mC0dot31zd9/r2lv6nCxXPk4fwoH6Dl8rg==
/*eslint no-return-assign: ["error", "always"]*/
function doSomething() {
return foo = bar + 2;
}
function doSomething() {
return foo += 2;
}
function doSomething() {
return (foo = bar + 2);
}
c8bJzypGHof5srMaCIwW3bARTgMjiqrOlEZgbZBbHDwGCzBTV32F4MPk0XWOvTc4kzzis7dlyAPRDUCCmT4r+A==
/*eslint no-return-assign: ["error", "always"]*/
function doSomething() {
return foo == bar + 2;
}
function doSomething() {
return foo === bar + 2;
}
何时不使用
vUQ8oXaTqAsV4+5yYYmHxrnrpQC3VUoDiBa/ANL7h8drutf9ZTmf7MYo6yC1TkaoFLQX+ymaL69vhhbe+Q5oK7jtRSVBaGo1RtaR7y4n2KkDCVlG3owf1RaGtSIwNk9YI2wx28HdND/E79VjHQHx19RKtdb14x9Mnn/nN56DkYQ=