tslint / codelyzer / ng lint error: “for (… in …) statements must be filtered with an if statement”

前端 未结 6 590
广开言路
广开言路 2020-12-07 09:33

Lint error message:

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

6条回答
  •  春和景丽
    2020-12-07 09:35

    To explain the actual problem that tslint is pointing out, a quote from the JavaScript documentation of the for...in statement:

    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).

    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).

    First solution

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

    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).

    Second solution

    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.

提交回复
热议问题