tslint/codelyzer/ng lint错误:"for(... in ...)语句必须使用if语句进行过滤" [英] tslint / codelyzer / ng lint error: "for (... in ...) statements must be filtered with an if statement"

查看:384
本文介绍了tslint/codelyzer/ng lint错误:"for(... in ...)语句必须使用if语句进行过滤"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

棉绒错误消息:

src/app/detail/edit/edit.component.ts [111,5]:用于(...在...中) 语句必须使用if语句进行过滤

src/app/detail/edit/edit.component.ts[111, 5]: for (... in ...) statements must be filtered with an if statement

代码段(这是一个有效的代码.也可以在 angular.io表单验证部分):

Code snippet (It is a working code. It is also available at angular.io form validation section):

for (const field in this.formErrors) {
      // clear previous error message (if any)
      this.formErrors[field] = '';
      const control = form.get(field);

      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }

任何想法如何解决此皮棉错误?

Any idea how to fix this lint error?

推荐答案

解释tslint指出的实际问题,请引述 ...中的JavaScript文档...在声明中:

循环将遍历对象的所有可枚举属性 本身以及对象从其构造函数的原型继承的对象 (更接近原型链中对象的属性会覆盖 原型的属性).

The loop will iterate over all enumerable properties of the object itself and those the object inherits from its constructor's prototype (properties closer to the object in the prototype chain override prototypes' properties).

因此,基本上,这意味着您将获得(从对象的原型链中)可能无法获得的属性.

So, basically this means you'll get properties you might not expect to get (from the object's prototype chain).

要解决这个问题,我们只需要迭代对象自身的属性即可.我们可以通过两种不同的方式来完成此操作(如@Maxxx和@Qwertiy所建议的那样).

To solve this we need to iterate only over the objects own properties. We can do this in two different ways (as suggested by @Maxxx and @Qwertiy).

for (const field of Object.keys(this.formErrors)) {
    ...
}

在这里,我们利用 Object.Keys()方法,该方法返回给定对象自己的可枚举属性的数组,其顺序与for ... in循环所提供的顺序相同(不同之处在于,for-in循环也枚举了原型链中的属性)

Here we utilize the Object.Keys() method which returns an array of a given object's own enumerable properties, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

for (var field in this.formErrors) {
    if (this.formErrors.hasOwnProperty(field)) {
        ...
    }
}

在此解决方案中,我们迭代对象的所有属性,包括其原型链中的属性,但使用

In this solution we iterate all of the object's properties including those in it's prototype chain but use the Object.prototype.hasOwnProperty() method, which returns a boolean indicating whether the object has the specified property as own (not inherited) property, to filter the inherited properties out.

这篇关于tslint/codelyzer/ng lint错误:"for(... in ...)语句必须使用if语句进行过滤"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆