【问题标题】:Javascript - catching error if json key does not existJavascript - 如果 json 键不存在则捕获错误
【发布时间】:2019-03-03 19:51:51
【问题描述】:

我正在尝试捕获来自 API 的 json 中不存在某个键时的错误,在本例中为 imageLinks.thumbnail。

这是我到目前为止写的,但我仍然收到 TypeError: Cannot read property 'thumbnail' of undefined.

            let cover;
            if(results.imageLinks === undefined){

                let cover = "http://actar.com/wp-content/uploads/2015/12/nocover.jpg";

            } else {
                let cover = results.imageLinks.thumbnail;
            };

我们将不胜感激。

干杯

【问题讨论】:

  • 这是非常少的调试信息,您介意添加什么是results,它包含什么?我不明白为什么要在 3 个不同的地方使用let cover,因为每次你这样做时,如果你想使用相同的变量,它就会产生新的变量,只需定义一次并使用它。
  • 您确定您在该行收到该错误吗?你在其他地方引用它吗?注意:这个问题与从 API 获取 JSON 无关。您正在处理 JavaScript 对象,而不是 JSON。
  • 如果 results.imageLinks 未定义,它将永远不会执行 else 块。

标签: javascript node.js json error-handling


【解决方案1】:

你可以使用IN操作符

if('imageLinks' in results)

【讨论】:

    【解决方案2】:

    使用hasOwnProperty()

    (function() {
      let cover;
      const result = {
        imageLinks: {}
      };
      if (!Object.hasOwnProperty.call(result, 'imageLinks')) {
        return;
      }
      if (Object.hasOwnProperty.call(result.imageLinks, 'thumbnail')) {
        cover = results.imageLinks.thumbnail;
      } else {
        cover = "http://actar.com/wp-content/uploads/2015/12/nocover.jpg";
      }
      console.log(cover);
    })();

    【讨论】:

      【解决方案3】:

      您的问题似乎有点模棱两可。
      我将尝试根据我从您的代码中理解的内容来回答。
      您似乎有一个名为 results 的对象,它可能有也可能没有属性 imageLinks。
      因此,您需要检查“如果结果具有属性 imageLinks 将封面分配给 results.imageLinks.thumbnail 否则分配“http://actar.com/wp-content/uploads/2015/12/nocover.jpg

      let cover = results['imageLinks']['thumbnail'] ? results['imageLinks']['thumbnail'] : "http://actar.com/wp-content/uploads/2015/12/nocover.jpg";
      

      请注意,我放置的支票更全面。仅当对象的结构为 {'results' : 'imageLinks': {'thumbnail' : 'some value'}}
      如果您只想检查“imageLinks”,则将结果['imageLinks']['thumbnail'] 替换为 results['imageLinks']
      在 JS 中你想检查对象中的键,你可以直接写 if(results['imageLinks'])

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-12-08
        • 1970-01-01
        • 2021-10-03
        • 2021-07-26
        • 1970-01-01
        • 2021-12-09
        • 1970-01-01
        相关资源
        最近更新 更多