0

我在使用TSlint时遇到问题,并理解为什么for(i=0; ...)不再允许循环。

假设我有一个简单的代码,例如:

this.filters['1','2','3'....];
for (let i = 0; i < this.filters.length; i++) {
      if (this.filters[i] === '2') {
        this.filters = new_value;
      }
    }

TSlint要求我将其转换为for -of。但是,使用for-of不起作用,因为我需要修改值并且 for-of 不允许修改。我可以使用类似的东西

for (const [i, el] of this.filters.entries()) { 

但随后我收到编译警告 TypeScript and Iterator: Type 'IterableIterator<T>'is not an array type 我必须更改编译选项。另外,我可以迭代keys()我认为有点愚蠢的for(const i=0...)

有人可以解释一下为什么TSlint仍然在抱怨这个以及为什么不允许使用for(const i=0; ....)

此外,我刚刚看到如果在for-of中执行此代码

this.filters['1','2','3'....];
for (let f of this.filters) {
      if (f === '2') {
        f = new_value;
      }
    }

我最终会得到相同的数组,因为它在循环之后没有被修改,但是,如果我有类似的方法但使用对象

let filters = [{id:'1'},{id:'2'},{id:'3'}];
console.log(filters)
for (let f of filters) {
      if (f.id === '2') {
        f.id = 'toto';
      }
    }
console.log(filters)

惊喜,我的对象数组在循环之后被修改了!有人可以解释一下为什么吗?

谢谢

我搜索了该错误,并在 github 中将其视为已关闭的问题,但我找不到解决方案 https://github.com/palantir/tslint/pull/1813

4

1 回答 1

1

使用字符串,您将获得以下信息:

字符串分配给f. 然后将新值重新分配给f: f === '2'。但是数组中的字符串没有被触及。

与对象:

对对象的引用分配给f。然后对象被修改:f.id = 'toto'。由于数组仅包含对对象的引用 - 我们在数组中得到修改后的对象。

基本上答案是引用类型和值类型变量之间的差异。

在您的情况下,如果for (const [i, el] of this.filters.entries()) {由于 ts 设置而无法工作,您可以尝试:

arr.forEach((entry, index) => arr[index] = ...);

或更丑陋的东西:

for(entry of arr) {
    arr[arr.indexOf(entry)] = ...;
}
于 2019-09-12T13:29:06.580 回答