簡體   English   中英

"Vue.js 應用程序中的“TypeError:使用過濾方法時無法將未定義或 null 轉換為對象”"

[英]The "TypeError: Cannot convert undefined or null to object" when using filter method" in Vue.js application

代碼如下所示:

getSections () {
  if (!this.document) {
    return []
  }

  return Object.keys(this.document.Sections).filter(x => this.document.Sections[x])
}

正如消息所說,此錯誤來自將 null 傳遞給 Object.keys。 在控制台中試試:

Object.keys(null)

VM198:1 Uncaught TypeError: Cannot convert undefined or null to object
    at Function.keys (<anonymous>)

因此,在您的代碼中this.document.Sectionsnull

在這里,您可以選擇修復它。 希望能幫助到你。

function getSections() {
    return (this.document && this.document.Sections)
        ? Object.keys(this.document.Sections)
            .filter(x => this.document.Sections[x])
        : [];
}

在一個片段中看到它:

 var test = { document: { Sections: { a: 1, b: undefined, c: 3 } } }; function getSections() { return (test.document && test.document.Sections) ? Object.keys(test.document.Sections) .filter(x => test.document.Sections[x]) : []; } console.log(getSections())

您需要檢查this.document.Sections是否為空或未定義

getSections () {
  if (!this.document && !this.document.Sections) {
    return []
  }

  return Object.keys(this.document.Sections).filter(x => this.document.Sections[x])
}

[1,null,2,undefined,{},3].filter(x => isFinite(x) && x > 1)產生[2, 3]

[1,null,2,undefined,{},3].filter(x => x !== null && x != undefined)產生[1, 2, {}, 3]

只需在過濾器中指定正確的標准。

錯誤類型錯誤:無法在 DynamicListingComponent.push..\/src\/app\/shared\/dynamic-listing\/dynamic-listing.component.ts.DynamicListingComponent.ngOnInit 的 Function.keys () 處將 undefined 或 null 轉換為對象(dynamic-listing.component .ts:94:34) 在 checkAndUpdateDirectiveInline

ngOnInit(): void { const colspan = this.hasActions || this.hasCheckbox ? this.hasCheckbox && this.hasActions ? this.columnHeaders.length + 2:this.columnHeaders.length + 1:this.columnHeaders.length;

this.colspan = colspan;
this.dynamicColumns = Object.keys(this.data[0]).map((v) =>
  this.utils.getParsedName(v)
);

this.setupDynamicColumn();

該錯誤可以更有用地寫為:“您的變量之一為空或未定義”

可供選擇的並不多,但您需要進行一些本地調試才能確定哪個以及為什么。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM