for (let i = 0; i < state.columns.length; i++) {
var column = state.columns[i];
var sortIndex;
var fsColumn = firstSortColumns.find((v, i) => {
sortIndex = i;
return v.dataField === column.dataField;
});
if (fsColumn) {
//...
} else {
//...
}
}
Function declared in a loop contains unsafe references to variable(s) 'sortIndex', 'column'.
I am getting a warning like this, how can i fix this?
for (let i = 0; i < state.columns.length; i++) {
var column = state.columns[i];
var sortIndex;
var fsColumn = firstSortColumns.find((v, i) => {
sortIndex = i;
return v.dataField === column.dataField;
});
if (fsColumn) {
//...
} else {
//...
}
}
Function declared in a loop contains unsafe references to variable(s) 'sortIndex', 'column'.
I am getting a warning like this, how can i fix this?
Share Improve this question edited Mar 14, 2022 at 11:28 asked Mar 14, 2022 at 11:25 user15621717user15621717 7-
1
I would suggest using
.findIndex()
instead of.find()
, and then using the index you get back to getfsColumn
– Nick Parsons Commented Mar 14, 2022 at 11:30 -
(v, i) => ...
creates a new variablei
with the same name as the loop variable. You could be a bit more imaginitive and use a different variable name. perhaps you could usej
instead! – phuzi Commented Mar 14, 2022 at 11:30 -
@phuzi Well, the
i
overshadows the otheri
, but that won’t lead to problems. – Sebastian Simon Commented Mar 14, 2022 at 11:30 -
2
I would urge you to avoid
var
pletely. Always useconst
. If you can’t useconst
, uselet
. – Sebastian Simon Commented Mar 14, 2022 at 11:31 -
2
@phuzi The linter doesn’t plain about
i
; it plains aboutcolumn
andsortIndex
, because they’re not scoped to the iteration but to the surrounding function (or global scope). – Sebastian Simon Commented Mar 14, 2022 at 11:33
2 Answers
Reset to default 4Your linter is being overly cautious here. Since the function you pass to find
isn't called asynchronously, the fact the value of column
can change isn't a problem.
If it were async then you could solve the problem by using let
instead of var
since it has block-scope instead of function-scope (and doing so would shut up your linter).
Declare variables outside of the iteration (loop) and modify inside the for loop.
var column, fsColumn, sortIndex;
for (let i = 0; i < state.columns.length; i++) {
column = state.columns[i];
sortIndex;
fsColumn = firstSortColumns.find((v, i) => {
sortIndex = i;
return v.dataField === column.dataField;
});
if (fsColumn) {
//...
} else {
//...
}
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745086759a4610450.html
评论列表(0条)