【发布时间】:2016-04-19 11:36:47
【问题描述】:
我正在转换一些现有代码以遵循 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;
}
对于resultArray的声明,ESLint抛出错误
ESLint: `resultArray` is never modified, use `const`instead. (prefer-const)
但是既然元素被压入数组,它不是被修改了吗?
【问题讨论】:
-
但它仍然是同一个数组对象,所以指向该对象的指针是一个常量。
-
啊!即使对象的内容可能会改变,指向该对象的引用/指针保持不变,因此最好使用 const。如果引用正在更改,例如resultArray = someOtherArray,然后使用 let 就可以了。明白了!
标签: javascript arrays ecmascript-6 eslint