Содержание
- Error unary operator used no plusplus
- When do I get this error?
- Why do I get this error?
- About the author
- Fix ESLint no-plusplus and no-param-reassign linter errors when adding to accumulator in reduce function
- 1 Answer 1
- no-plusplus with ‘allowForLoopAfterthoughts’: true fails if the afterthought contains multiple ++ or — statements #13005
- Comments
- no-plusplus
- Почему ESLint не плюсуется?
- Как отключить правило ESLint?
- Как обойти ESLint?
- Как исправить ошибки ESLint?
- Как узнать,работает ли ESLint?
- Как исправить проблемы ESLint в Vscode?
- Как отключить Vscode ESLint?
- Rule Details
- Options
- allowForLoopAfterthoughts
- ошибка eslint Унарный оператор ‘++’ использовал no-plusplus
- 5 ответов
Error unary operator used no plusplus
This warning has existed in two forms in JSLint and ESLint. It was introduced in the original version of JSLint and has remained in both tools since. It is not present in JSHint.
In JSLint the warning given is «Unexpected ‘++’» (or «Unexpected ‘—‘»)
In ESLint the message has always been «Unary operator ‘++’ used» (or «Unary operator ‘—‘ used»)
The situations that produce the warning have not changed despite changes to the text of the warning itself.
When do I get this error?
The «Unexpected ‘++’» error, and the alternative «Unary operator ‘++’ used», is thrown when JSLint or ESLint encounters a use of the increment or decrement operators. In ESLint the warning is only raised if the no-plusplus option is set to 1 . Here’s an example:
Why do I get this error?
This error message is perhaps the most debated of all JSLint error messages. It exists solely to warn you that JSLint has encountered a violation of a specific coding style. The style in question is the style of the author of JSLint, Douglas Crockford. For his reasoning, you can read the JSLint documentation:
The ++ (increment) and — (decrement) operators have been known to contribute to bad code by encouraging excessive trickiness. They are second only to faulty architecture in enabling to viruses and other security menaces. Also, preincrement/postincrement confusion can produce off-by-one errors that are extremely difficult to diagnose.
There are many JavaScript developers who disagree with that, but the fact remains, it’s a rule in JSLint so you need a way to work around it. What JSLint would prefer you to do is use the normal addition and subtraction operators, which can be combined with the assignment operator for a slight decrease in length:
If you would prefer not to do that, and would rather stick with the normal increment and decrement operators, you can set the plusplus option to true to tell JSLint to allow them:
In ESLint the rule that generates this warning is named no-plusplus . You can disable it by setting it to 0 , or enable it by setting it to 1 .
This article was written by James Allardice, Software engineer at Tesco and orangejellyfish in London. Passionate about React, Node and writing clean and maintainable JavaScript. Uses linters (currently ESLint) every day to help achieve this.
This project is supported by orangejellyfish, a London-based consultancy with a passion for JavaScript. All article content is available on GitHub under the Creative Commons Attribution-ShareAlike 3.0 Unported licence.
Have you found this site useful?
Please consider donating to help us continue writing and improving these articles.
Источник
Fix ESLint no-plusplus and no-param-reassign linter errors when adding to accumulator in reduce function
Give this code in TypeScript:
How do I stop the linter throwing these two errors?
(parameter) acc: number Unary operator ‘++’ used. eslint no-plusplus
Assignment to function parameter ‘acc’. eslint no-param-reassign
1 Answer 1
A reduce callback accepts an accumulator and the current value as arguments and returns the accumulator for the next iteration, or the accumulator as a result if there is no next iteration. There is no reason to mutate any of the arguments.
The no-plusplus rule, additionally, disallows syntax like ++acc .
Since there is no need to mutate acc to begin with, the minimal fix for both errors would be:
This returns acc incremented by 1 if cur.id is truthy, and the current acc , otherwise, as expected. Your version mutates the current acc in addition to returning the incremented acc , but there is no reason to do so.
If you’re using ESLint, you have to be aware of the rules. You can’t write code that ESLint complains about and then be confused why ESLint complains about your code. Every rule has its own article explaining the rationale, listing alternatives, and explaining how the rule can be adjusted or disabled.
For example, you can disable the no-param-reassign rule
- by including the comment // eslint-disable no-param-reassign at the top of your file,
- or // eslint-disable-next-line no-param-reassign one line above a usage,
- or // eslint-disable-line no-param-reassign in the line after a usage,
- or by disabling it in your .eslintrc file.
There’s also a rule that would disallow conditional expressions and some variants. You can further simplify your function to avoid even that:
This would have the same semantics, but it’s still not quite clear what kind of condition cur.id was supposed to be. It’s best practice to make that a little more explicit (especially in TypeScript), e.g. cur.hasOwnProperty(«id») or cur.id !== 0 or cur.id !== «» , depending on what cur.id may be. Then, the Boolean call is no longer necessary; for example, if you want to count how many objects in arr have an id own property, use this instead:
If you still want to use your original falsy / truthy check, the code can be shortened to one of these, using destructuring assignment:
Источник
no-plusplus with ‘allowForLoopAfterthoughts’: true fails if the afterthought contains multiple ++ or — statements #13005
Tell us about your environment
- ESLint Version: 6.8.0
- Node Version: 10.15.3
- npm Version: 6.4.1
What parser (default, Babel-ESLint, etc.) are you using?
babel-eslint
Please show your full configuration:
What did you do? Please include the actual source code causing the issue, as well as the command that you used to run ESLint.
What did you expect to happen?
Expected eslint not to error on i++ and j++ because < ‘allowForLoopAfterthoughts’: true >is specified
What actually happened? Please include the actual, raw output from ESLint.
I was able to fix the warning by changing i++, j++ -> i += 1, j += 1 , but this is something of an antipattern.
Yes, there are other ways to write this, i.e.
work just fine, but:
a) I’m updating eslint on a large codebase, so I’d prefer to make as few changes as possible.
b) refactors for this simple example aside, this feels like a bug to me.
If this is the intended behaviour because as touched on in the no-plusplus docs there are unintended consequences, then I’d suggest updating that doc to specifically call out that you can only override this rule if the for loop afterthought consists only of one single ++ or — . (for example, changing the for loop to the hideous . ; i += 1, j++) as an experiment still errors on j++ because the afterthought is a larger expression)
The text was updated successfully, but these errors were encountered:
Источник
no-plusplus
++ and — » onmousemove=»i18n(this)»>Запретить унарные операторы ++ и —
Почему ESLint не плюсуется?
Как отключить правило ESLint?
Как обойти ESLint?
Как исправить ошибки ESLint?
Как узнать,работает ли ESLint?
Как исправить проблемы ESLint в Vscode?
Как отключить Vscode ESLint?
++ and — operators are subject to automatic semicolon insertion, differences in whitespace can change semantics of source code.» onmousemove=»i18n(this)»>Поскольку унарные операторы ++ и — автоматически вставляются точкой с запятой, различия в пробелах могут изменить семантику исходного кода.
Rule Details
++ and — .» onmousemove=»i18n(this)»>Это правило запрещает унарные операторы ++ и — .
Примеры неправильного кода для этого правила:
Примеры правильного кода для этого правила:
Options
Это правило имеет опцию объекта.
- «allowForLoopAfterthoughts»: true allows unary operators ++ and — in the afterthought (final expression) of a for loop.’ onmousemove=»i18n(this)»> «allowForLoopAfterthoughts»: true разрешает унарные операторы ++ и — в запоздалой мысли (заключительном выражении) цикла for .
allowForLoopAfterthoughts
< «allowForLoopAfterthoughts»: true >option:’ onmousemove=»i18n(this)»>Примеры правильного кода для этого правила с параметром < «allowForLoopAfterthoughts»: true >:
< «allowForLoopAfterthoughts»: true >option:’ onmousemove=»i18n(this)»>Примеры некорректного кода для этого правила с параметром < «allowForLoopAfterthoughts»: true >:
Источник
ошибка eslint Унарный оператор ‘++’ использовал no-plusplus
Я получаю сообщение об ошибке с моим циклом for, если я использовал i++ для loop
5 ответов
Одним из вариантов может быть замена i++ на i+=1 .
Вы также можете отключить это конкретное правило eslint (либо для конкретной строки, либо для файла, либо для глобальной конфигурации). Учтите, что это может быть не рекомендуется, особенно на уровне файла или строки.
Название правила, которое вы ищете, — no-plusplus.
Отключить глобально
В конфигурационный файл eslint добавьте следующее:
Существует также возможность отключить его только для циклов for:
Для получения дополнительной информации вы можете проверить документацию eslint no-plusplus.
Отключить на уровне файла
В верхней части файла добавьте следующее:
Отключить для данной строки
Непосредственно перед циклом for добавьте следующее:
Я получил решение этой проблемы
Если мы используем i++ в нашем коде, eslint выдает ошибку. Чтобы избежать этого типа ошибки, мы должны использовать
Как видите, это ошибка линтинга. Либо напишите такой код,
Или отключите это правило eslint. (не хорошая идея);
Согласно документу Eslint, использование этих операторов требует автоматической вставки точки с запятой, а различия в пробелах могут изменить семантику исходного кода.
Таким образом, это не разрешено в правиле eslint, но вы можете игнорировать его, используя эту строку:
eslint no-plusplus: «ошибка»
Будет выдавать ошибку в следующих экземплярах
Используйте следующее, чтобы исправить проблемы с ворсом, чтобы он соответствовал правилам
Источник
History
This warning has existed in two forms in JSLint and ESLint. It was introduced in
the original version of JSLint and has remained in both tools since. It is not
present in JSHint.
-
In JSLint the warning given is «Unexpected ‘++'» (or «Unexpected ‘—‘»)
-
In ESLint the message has always been «Unary operator ‘++’ used» (or «Unary
operator ‘—‘ used»)
The situations that produce the warning have not changed despite changes to the
text of the warning itself.
When do I get this error?
The «Unexpected ‘++'» error, and the alternative «Unary operator ‘++’ used», is
thrown when JSLint or ESLint encounters a use of the increment or decrement
operators. In ESLint the warning is only raised if the no-plusplus option is
set to 1. Here’s an example:
var x = 1,
y = 10;
x++;
y--;
Why do I get this error?
This error message is perhaps the most debated of all JSLint error messages. It
exists solely to warn you that JSLint has encountered a violation of a
specific coding style. The style in question is the style of the author of
JSLint, Douglas Crockford. For his reasoning, you can read the JSLint
documentation:
The ++ (increment) and — (decrement) operators have been known to contribute
to bad code by encouraging excessive trickiness. They are second only to
faulty architecture in enabling to viruses and other security menaces. Also,
preincrement/postincrement confusion can produce off-by-one errors that are
extremely difficult to diagnose.
There are many JavaScript developers who disagree with that, but the fact
remains, it’s a rule in JSLint so you need a way to work around it. What JSLint
would prefer you to do is use the normal addition and subtraction operators,
which can be combined with the assignment operator for a slight decrease in
length:
var x = 1,
y = 10;
x = x + 1; // or x += 1;
y = y - 1; // or y -= 1;
If you would prefer not to do that, and would rather stick with the normal
increment and decrement operators, you can set the plusplus option to true
to tell JSLint to allow them:
/*jslint plusplus: true */
var x = 1,
y = 10;
x++;
y--;
In ESLint the rule that generates this warning is named no-plusplus. You
can disable it by setting it to 0, or enable it by setting it to 1.
Disallow the unary operators ++ and --
Because the unary ++ and -- operators are subject to automatic semicolon insertion, differences in whitespace can change semantics of source code.
var i = 10;var j = 20;i ++j// i = 11, j = 20
var i = 10;var j = 20;i++j// i = 10, j = 21
Rule Details
This rule disallows the unary operators ++ and --.
Examples of incorrect code for this rule:
/*eslint no-plusplus: "error"*/var foo = 0;foo++;var bar = 42;bar--;for (i = 0; i < l; i++) { return;}
Examples of correct code for this rule:
/*eslint no-plusplus: "error"*/var foo = 0;foo += 1;var bar = 42;bar -= 1;for (i = 0; i < l; i += 1) { return;}
Options
This rule has an object option.
-
"allowForLoopAfterthoughts": trueallows unary operators++and--in the afterthought (final expression) of aforloop.
allowForLoopAfterthoughts
Examples of correct code for this rule with the { "allowForLoopAfterthoughts": true } option:
/*eslint no-plusplus: ["error", { "allowForLoopAfterthoughts": true }]*/for (i = 0; i < l; i++) { doSomething(i);}for (i = l; i >= 0; i--) { doSomething(i);}for (i = 0, j = l; i < l; i++, j--) { doSomething(i, j);}
Examples of incorrect code for this rule with the { "allowForLoopAfterthoughts": true } option:
/*eslint no-plusplus: ["error", { "allowForLoopAfterthoughts": true }]*/for (i = 0; i < l; j = i++) { doSomething(i, j);}for (i = l; i--;) { doSomething(i);}for (i = 0; i < l;) i++;
Version
This rule was introduced in ESLint v0.0.9.
Resources
- Rule source
- Tests source
ESLint
8.30
-
no-octal-escape
Disallow octal escape sequences in string literals As of the ECMAScript 5 specification, octal escape sequences in string literals are deprecated and should
-
no-param-reassign
Disallow reassigning function parameters Assignment to variables declared function parameters can be misleading and confusing behavior, modifying will
-
no-promise-executor-return
Disallow returning values from Promise executor functions The new Promise constructor accepts single argument, called an executor.
-
no-proto
Disallow the use of __proto__ property __proto__ property has been deprecated of ECMAScript 3.1 and shouldn’t used in the code.
Error unary operator used no plusplus
This warning has existed in two forms in JSLint and ESLint. It was introduced in the original version of JSLint and has remained in both tools since. It is not present in JSHint.
In JSLint the warning given is «Unexpected ‘++’» (or «Unexpected ‘—‘»)
In ESLint the message has always been «Unary operator ‘++’ used» (or «Unary operator ‘—‘ used»)
The situations that produce the warning have not changed despite changes to the text of the warning itself.
When do I get this error?
The «Unexpected ‘++’» error, and the alternative «Unary operator ‘++’ used», is thrown when JSLint or ESLint encounters a use of the increment or decrement operators. In ESLint the warning is only raised if the no-plusplus option is set to 1 . Here’s an example:
Why do I get this error?
This error message is perhaps the most debated of all JSLint error messages. It exists solely to warn you that JSLint has encountered a violation of a specific coding style. The style in question is the style of the author of JSLint, Douglas Crockford. For his reasoning, you can read the JSLint documentation:
The ++ (increment) and — (decrement) operators have been known to contribute to bad code by encouraging excessive trickiness. They are second only to faulty architecture in enabling to viruses and other security menaces. Also, preincrement/postincrement confusion can produce off-by-one errors that are extremely difficult to diagnose.
There are many JavaScript developers who disagree with that, but the fact remains, it’s a rule in JSLint so you need a way to work around it. What JSLint would prefer you to do is use the normal addition and subtraction operators, which can be combined with the assignment operator for a slight decrease in length:
If you would prefer not to do that, and would rather stick with the normal increment and decrement operators, you can set the plusplus option to true to tell JSLint to allow them:
In ESLint the rule that generates this warning is named no-plusplus . You can disable it by setting it to 0 , or enable it by setting it to 1 .
About the author
This article was written by James Allardice, Software engineer at Tesco and orangejellyfish in London. Passionate about React, Node and writing clean and maintainable JavaScript. Uses linters (currently ESLint) every day to help achieve this.
This project is supported by orangejellyfish, a London-based consultancy with a passion for JavaScript. All article content is available on GitHub under the Creative Commons Attribution-ShareAlike 3.0 Unported licence.
Have you found this site useful?
Please consider donating to help us continue writing and improving these articles.
Источник
Name already in use
jslint-error-explanations / message-articles / unexpected-increment.md
- Go to file T
- Go to line L
- Copy path
- Copy permalink
Copy raw contents
Copy raw contents
This warning has existed in two forms in JSLint and ESLint. It was introduced in the original version of JSLint and has remained in both tools since. It is not present in JSHint.
In JSLint the warning given is «Unexpected ‘++’» (or «Unexpected ‘—‘»)
In ESLint the message has always been «Unary operator ‘++’ used» (or «Unary operator ‘—‘ used»)
The situations that produce the warning have not changed despite changes to the text of the warning itself.
When do I get this error?
The «Unexpected ‘++’» error, and the alternative «Unary operator ‘++’ used», is thrown when JSLint or ESLint encounters a use of the increment or decrement operators. In ESLint the warning is only raised if the no-plusplus option is set to 1 . Here’s an example:
Why do I get this error?
This error message is perhaps the most debated of all JSLint error messages. It exists solely to warn you that JSLint has encountered a violation of a specific coding style. The style in question is the style of the author of JSLint, Douglas Crockford. For his reasoning, you can read the JSLint documentation:
The ++ (increment) and — (decrement) operators have been known to contribute to bad code by encouraging excessive trickiness. They are second only to faulty architecture in enabling to viruses and other security menaces. Also, preincrement/postincrement confusion can produce off-by-one errors that are extremely difficult to diagnose.
There are many JavaScript developers who disagree with that, but the fact remains, it’s a rule in JSLint so you need a way to work around it. What JSLint would prefer you to do is use the normal addition and subtraction operators, which can be combined with the assignment operator for a slight decrease in length:
If you would prefer not to do that, and would rather stick with the normal increment and decrement operators, you can set the plusplus option to true to tell JSLint to allow them:
In ESLint the rule that generates this warning is named no-plusplus . You can disable it by setting it to 0 , or enable it by setting it to 1 .
Источник
no-plusplus with ‘allowForLoopAfterthoughts’: true fails if the afterthought contains multiple ++ or — statements #13005
Comments
erhsparks commented Mar 6, 2020 •
Tell us about your environment
- ESLint Version: 6.8.0
- Node Version: 10.15.3
- npm Version: 6.4.1
What parser (default, Babel-ESLint, etc.) are you using?
babel-eslint
Please show your full configuration:
What did you do? Please include the actual source code causing the issue, as well as the command that you used to run ESLint.
What did you expect to happen?
Expected eslint not to error on i++ and j++ because < ‘allowForLoopAfterthoughts’: true >is specified
What actually happened? Please include the actual, raw output from ESLint.
I was able to fix the warning by changing i++, j++ -> i += 1, j += 1 , but this is something of an antipattern.
Yes, there are other ways to write this, i.e.
work just fine, but:
a) I’m updating eslint on a large codebase, so I’d prefer to make as few changes as possible.
b) refactors for this simple example aside, this feels like a bug to me.
If this is the intended behaviour because as touched on in the no-plusplus docs there are unintended consequences, then I’d suggest updating that doc to specifically call out that you can only override this rule if the for loop afterthought consists only of one single ++ or — . (for example, changing the for loop to the hideous . ; i += 1, j++) as an experiment still errors on j++ because the afterthought is a larger expression)
The text was updated successfully, but these errors were encountered:
Источник
no-plusplus
++ and — » onmousemove=»i18n(this)»>Запретить унарные операторы ++ и —
Почему ESLint не плюсуется?
Как отключить правило ESLint?
Как обойти ESLint?
Как исправить ошибки ESLint?
Как узнать,работает ли ESLint?
Как исправить проблемы ESLint в Vscode?
Как отключить Vscode ESLint?
++ and — operators are subject to automatic semicolon insertion, differences in whitespace can change semantics of source code.» onmousemove=»i18n(this)»>Поскольку унарные операторы ++ и — автоматически вставляются точкой с запятой, различия в пробелах могут изменить семантику исходного кода.
Rule Details
++ and — .» onmousemove=»i18n(this)»>Это правило запрещает унарные операторы ++ и — .
Примеры неправильного кода для этого правила:
Примеры правильного кода для этого правила:
Options
Это правило имеет опцию объекта.
- «allowForLoopAfterthoughts»: true allows unary operators ++ and — in the afterthought (final expression) of a for loop.’ onmousemove=»i18n(this)»> «allowForLoopAfterthoughts»: true разрешает унарные операторы ++ и — в запоздалой мысли (заключительном выражении) цикла for .
allowForLoopAfterthoughts
< «allowForLoopAfterthoughts»: true >option:’ onmousemove=»i18n(this)»>Примеры правильного кода для этого правила с параметром < «allowForLoopAfterthoughts»: true >:
< «allowForLoopAfterthoughts»: true >option:’ onmousemove=»i18n(this)»>Примеры некорректного кода для этого правила с параметром < «allowForLoopAfterthoughts»: true >:
Источник
Name already in use
jslint-error-explanations / message-articles / confusing-pluses.md
- Go to file T
- Go to line L
- Copy path
- Copy permalink
Copy raw contents
Copy raw contents
This warning has existed in a few forms in both JSLint and JSHint. It was introduced in the original version of JSLint and has remained in both tools ever since.
In JSHint prior to version 1.0.0 the warning given was «Confusing plusses»
In JSHint 1.0.0 and above the spelling has been corrected and the message used is now «Confusing pluses»
JSLint has always used the more generic «Confusing use of ‘» warning in the same situation
When do I get this error?
The «Confusing pluses» error is thrown when JSHint encounters an addition operator in which the right-hand-side expression is preceded by the unary + operator. In the following example we attempt to compute the addition of a numeric literal and the numeric value of a variable:
Why do I get this error?
This error is raised to highlight a potentially confusing piece of code. Your code will most likely run as expected but it could cause issues with maintenance and be confusing to other developers.
The + operator is overloaded in JavaScript. Most commonly it can be seen as the addition operator but it also functions in a unary form as a numeric casting operator. In this unary form the result of the expression will be the value of the operand coerced to the Number type. In the example above, because the value of a is a string that can be converted to a number, the +a expression results in the value 5 and the value of b ends up as 10 .
This behaviour is described in the specification (ES5 §11.4.6):
The production UnaryExpression : + UnaryExpression is evaluated as follows:
- Let expr be the result of evaluating UnaryExpression.
- Return ToNumber(GetValue(expr))
However, when the addition operator is used adjacent to the unary + operator an unforunate resemblance to the increment operator arises. The increment operator, ++ , is used to add 1 to its operand. It can be used as a postfix or prefix operator which means it can appear after or before its operand. This makes the above example slightly confusing on first glance, especially as the ++ operator is far more commonly used than the unary + operator.
To resolve this issue the easiest fix is to wrap the unary expression in parentheses to disambiguate the + characters:
In JSHint 1.0.0 and above you have the ability to ignore any warning with a special option syntax. The identifier of this warning is W007. This means you can tell JSHint to not issue this warning with the /*jshint -W007 */ directive.
Источник

