【问题标题】:Best way to address "cannot read property * of undefined"?解决“无法读取未定义的属性 *”的最佳方法?
【发布时间】:2016-07-21 03:31:37
【问题描述】:

这个错误在javascript开发中经常出现。

无法读取未定义的属性连接

有没有解决这个问题的最佳方法?

我使用的一些技术是:

初始化

question.tags = question.tags || [];
console.log(question.tags.join(', ');

If 语句

if(question.tags) {
  console.log(question.tags.join(', ');
}

【问题讨论】:

  • “最佳方式”完全取决于您的程序和数据的目的。
  • 到底是什么问题?

标签: javascript coding-style


【解决方案1】:

您可以使用if..elseObject.hasOwnProperty()Array.isArray() 来确定@​​987654324@ 是否存在以及对象是否具有属性tagsquestion.tags 是一个数组

if (typeof question === "object" 
    && question.hasOwnProperty("tags") 
    && Array.isArray(question.tags)) {
  //do stuff
} else {
  // do other stuff, e.g
  // question = {};
  // question.tags = [];
}

【讨论】:

    【解决方案2】:

    没有具体和准确的方法来做到这一点。如果存在 Array 或 Object 或 String 的实例,它将继承原型函数。就像数组的实例有一个 splice(),String 的实例有一个 replace()。

    现在当这个实例未定义时,它会抛出 JS 错误。让我们假设a 应该是一个数组。您可以通过逻辑 ||

    进行脏检查
    (a || []).length;
    

    或 if 块或三元属性

    return a ? a.length || undefined;
    

    或类型检查

    (Array.isArray(a) || []).length
    

    【讨论】:

      【解决方案3】:
      question.tags ? question.tags : []
      

      【讨论】:

        【解决方案4】:

        您可以在 if 条件中使用 === 和 !== 运算符,例如

          if(object.property !== undefined)
             {
               ///write your code here
              }
        

        此运算符将匹配您的值 + 类型,因此很容易识别提到的属性是否未定义..希望这会有所帮助:)

        【讨论】:

          猜你喜欢
          • 2017-06-02
          • 2019-04-30
          • 1970-01-01
          • 1970-01-01
          • 2021-05-10
          • 2022-01-26
          • 2021-10-25
          • 2019-11-21
          • 2019-08-01
          相关资源
          最近更新 更多