ESLint表示数组从未修改,即使元素被推入数组 [英] ESLint says array never modified even though elements are pushed into array
问题描述
我正在转换一些现有的代码以遵循ECMA脚本,我正在使用ESLint遵循编码标准。我有以下ecmascript方法
I am converting some existing code to follow ECMA script and I am using ESLint to follow a coding standard. I have the following ecmascript method
static getArrayOfIndices(text, char) {
let resultArray = [];
let index = text.indexOf(char);
const lastIndex = text.lastIndexOf(char);
while (index <= lastIndex && index !== -1) {
resultArray.push(index);
if (index < lastIndex) {
index = text.substr(index + 1).indexOf(char) + index + 1;
} else {
index = lastIndex + 1999; // some random addition to fail test condition on next iteration
}
}
return resultArray;
}
对于声明resultArray,ESLint会抛出错误
For the declaration of resultArray, ESLint throws the error
ESLint: `resultArray` is never modified, use `const`instead. (prefer-const)
但是由于元素被推入数组,是不是被修改?
But since elements are being pushed into the array, isn't it being modified?
推荐答案
要了解此错误,您必须了解 const
声明的变量保持对值的只读引用。但这并不意味着它的价值是不可变的 [mdn article] 一>。
To understand this error you must understand that const
declared variables hold read-only references to a value. But it does not mean that the value it holds is immutable [mdn article].
由于您只是更改变量的成员,而是在绑定的 prefer-const
规则上执行重新分配的es-lint警告您,可以使用 const
声明的变量而不是 let
声明的变量。
Since you are only changing members of the variable but not performing a reassignment on the binding the prefer-const
rule of es-lint warns you that a const
declared variable could be used instead of a let
declared variable.
这篇关于ESLint表示数组从未修改,即使元素被推入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!