代码如下:
getSections () {
if (!this.document) {
return []
}
return Object.keys(this.document.Sections).filter(x => this.document.Sections[x])
}
this.document.Sections 是包含属性(也是对象)的对象。
如何消除这个错误?
最佳答案
正如消息所述,此错误来自将 null 传递给 Object.keys。在控制台中尝试一下:
Object.keys(null)
VM198:1 Uncaught TypeError: Cannot convert undefined or null to object
at Function.keys (<anonymous>)
因此,在您的代码中 this.document.Sections
为 null
。
在这里您可以选择修复它。希望对您有所帮助。
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())
关于javascript - Vue.js应用中使用filter方法时的 "TypeError: Cannot convert undefined or null to object",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56686692/