ESLint表示,即使将元素推入数组,数组也从未修改过

sha*_*shi 12 javascript arrays ecmascript-6 eslint

我正在转换一些现有代码以遵循ECMA脚本,我使用ESLint遵循编码标准.我有以下ecmascript方法

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;
  }
Run Code Online (Sandbox Code Playgroud)

对于resultArray的声明,ESLint会抛出错误

ESLint: `resultArray` is never modified, use `const`instead. (prefer-const)
Run Code Online (Sandbox Code Playgroud)

但是由于元素被推入数组,是不是被修改了?

Mat*_*isk 24

要理解此错误,您必须了解const声明的变量包含对值的只读引用.但这并不意味着它拥有的价值是不可改变的[mdn article].

由于您只是更改变量的成员,但没有对绑定执行重新分配,因此prefer-constes-lint规则会警告您const可以使用let声明的变量而不是声明的变量.