【问题标题】:typescript filter array on 2 parameters2个参数的打字稿过滤器数组
【发布时间】:2017-09-10 11:25:24
【问题描述】:

为了过滤可能包含 2 个参数的数组,我编写了以下代码:

filterStudies(searchString?: string) {
        if (searchString && !this.selectedModalityType) {
            this.studies = this.fullStudyList.filter(function (study) {
                return (study.Code.toUpperCase().includes(searchString.toUpperCase())) ||
                    (study.Description.toUpperCase().includes(searchString.toUpperCase()));
                })
        } else if (!searchString && this.selectedModalityType) {
            console.log(this.selectedModalityType)
            this.studies = this.fullStudyList.filter(function (study) {
                return (study.ModalityType.Code.toUpperCase() === this.selectedModalityType.toUpperCase())
            })
        } else if (searchString && this.selectedModalityType) {
            this.studies = this.fullStudyList.filter(function (study) {
                return (study.Code.toUpperCase().includes(searchString.toUpperCase())) ||
                    (study.Description.toUpperCase().includes(searchString.toUpperCase())) &&
                    (study.ModalityType.Code.toUpperCase() === this.selectedModalityType.toUpperCase())
            })
        }
    }

filterStudies(searchString?: string) 在输入文本框时调用。

另一种过滤方式是从下拉框中选择一个值。通过这段代码实现:

handleSelection(value:any){
            this.selectedModalityType = value;
            console.log(value)
            this.filterStudies()
        }

在点击此代码之前一切正常:

this.studies = this.fullStudyList.filter(function (study) {
                return (study.ModalityType.Code.toUpperCase() === this.selectedModalityType.toUpperCase())
            })

错误信息:ERROR TypeError: Cannot read property 'selectedModalityType' of undefined,我看到它实际上是在之前的行中记录的。

我错过了什么??

谢谢,

【问题讨论】:

    标签: arrays typescript filter


    【解决方案1】:

    在您的函数中,this 与之前的行不同。

    这将起作用:

    let self = this;
    this.studies = this.fullStudyList.filter(function (study) {
                    return (study.ModalityType.Code.toUpperCase() === self.selectedModalityType.toUpperCase())
                })
    

    您可以阅读本文以了解更多信息:https://github.com/Microsoft/TypeScript/wiki/%27this%27-in-TypeScript

    JavaScript(以及 TypeScript)中的 this 关键字的行为与许多其他语言中的行为不同。这可能非常令人惊讶,特别是对于其他语言的用户来说,他们对它应该如何工作有一定的直觉。 (...) 失去此上下文的典型症状包括:

    • 类字段 (this.foo) 在需要其他值时未定义

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-13
      • 1970-01-01
      • 2018-09-23
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      相关资源
      最近更新 更多