网站搜索

angular - 检查可选属性是否有值


我有以下接口:

export interface Development {
  id: number;
  type: string;
  value: string;
  formContent?: contentInterface;
}

并且 contentInterface 是一个具有以下内容的接口:

 export interface contentInterface {
   development: string;
   name: string;
   comment: string;
 }

现在当我做以下操作时:

  // tring to check if the next sectorForm[i] has formcontent values assigned
  // if values are available in formcontent add that to a form.

 if (typeof this.sectorForm[i + 1].formContent !== 'undefined') {  
  this.DevelopmentForm.setValue(this.sectorForm[i + 1].formContent);
 }

sectorForm 声明如下:sectorForm: Development[]

上述代码在最后一个索引处导致以下错误 ERROR TypeError: Cannot read property 'formContent' of undefined

答案#1

避免索引问题,可以这样做,利用 forEach

 this.sectorForm.forEach(form => {
   //rest code 
    if (form.formContent)  { 

    }
   });

就做这个

if (this.sectorForm[i + 1] && 
       this.sectorForm[i + 1].formContent) 

注意:如果你想检查对象上是否存在某个属性,可以使用 hasOwnProperty('property1')

它会检查 null 或 undefined 等。

答案#2

数组中的项可能为 null,你应当先检查这一点:

if (this.sectorForm[i + 1] && typeof this.sectorForm[i + 1].formContent !== 'undefined') {  
  this.DevelopmentForm.setValue(this.sectorForm[i + 1].formContent);
 }