javascript - Vue.js应用中使用filter方法时的 "TypeError: Cannot convert undefined or null to object"

标签 javascript vue.js

代码如下:

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

关于javascript - Vue.js应用中使用filter方法时的 "TypeError: Cannot convert undefined or null to object",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56686692/

相关文章:

javascript - 在输入字段上使用 vue 指令(v-model、@input)时,vue 中的数据列表出现意​​外行为?

vue.js - 在不重新安装组件的情况下更新 Vue Router?

javascript - JS - array.includes 问题

javascript - 为什么在使用 jQuery Gridly 插件后无法编辑 span?

javascript - 使用 KnockoutJS 绑定(bind)树结构的正确方法

javascript - HTML 实体到 Unicode 转义序列

javascript - 日期验证 - 仅输入当月内的日期

javascript - jQuery .text() 问题

javascript - 为什么 Node.js 无法处理 Vue.js 的请求?

javascript - Vue js -- 通过方法访问 props 失败