【问题标题】:Ternary operator - when variable is undefined三元运算符 - 当变量未定义时
【发布时间】:2022-10-18 02:42:45
【问题描述】:

我有一个 fn,它在调用时创建和填充变量 linkedinInsight

只是对这个 fn 的快速概述,它将检查响应数据并查看是否有匹配项。如果是,它将用数据填充linkedinInight 变量。

使用三元运算,当变量未定义时,我无法显示“未定义”。 linkedinInsight === undefined ? "undefined" : "Variable exist"

但是,如果 fn 匹配,我可以看到 "Variable exist" 显示。

在变量为undefined的情况下, 从控制台,它显示

Error handling response: TypeError: Cannot read properties of undefined (reading 'insight_tags')
    at chrome-extension://fpncfpgjnkfnlafmojhhpgophpgikaao/popup.js:13:60

这里的目标是呈现数据,如果我们找不到数据,我想返回“数据未找到消息”。

有帮助吗?

document.addEventListener(
  "DOMContentLoaded",
  function () {
    var checkPageButton = document.getElementById("clickIt");
    checkPageButton.addEventListener(
      "click",
      function () {
        chrome.tabs.getSelected(null, function (tab) {
          const backgroundPage = chrome.extension.getBackgroundPage();

          const linkedinInsight =
            backgroundPage["_linkedin_pixel_data"][tab.id].insight_tags;


          alert(
            linkedinInsight === undefined ? "undefined" : "Variable exist"
          );

【问题讨论】:

  • 也许尝试typeof linkedinInsight === 'undefined' 而不是linkedinInsight === undefined?你能告诉我这是否有效吗?
  • 问题在于在线backgroundPage["_linkedin_pixel_data"][tab.id].insight_tags; - backgroundPage["_linkedin_pixel_data"][tab.id] 返回undefined,因此当您尝试从中读取insight_tags 时,您会收到无法从undefined 读取insight_tags 的错误。
  • 是的,Vlaz 是对的。问题是没有读取insight_tags 的错误。
  • 解决方案:是为了确保我们解决错误。 const linkedinInsight = backgroundPage?.["_linkedin_pixel_data"]?.[tab.id]?.insight_tags;

标签: javascript google-chrome-extension conditional-operator


【解决方案1】:

问题在下面一行,替换

const linkedinInsight =
            backgroundPage["_linkedin_pixel_data"][tab.id].insight_tags;

const linkedinInsight =
            (backgroundPage && backgroundPage["_linkedin_pixel_data"] && backgroundPage["_linkedin_pixel_data"][tab.id] && backgroundPage["_linkedin_pixel_data"][tab.id].insight_tags) || undefined;

或者如果支持optional chaining

const linkedinInsight =
                backgroundPage?.["_linkedin_pixel_data"]?.[tab.id]?.insight_tags;

【讨论】:

    【解决方案2】:

    使用nullish coalescingm operator

    let exists = value ?? `${value} doesn't exist`;
    

    如果valueundefinednull 则返回运算符?? 右侧的值

    function check(X) {
      let present = X  ?? `"X" does not exist`;
      let limit = X < 10 && X > 0 ? `"X" is within range` :  `"X" is out of range`;
      if (typeof present == 'string') {
        console.log(present);
        return;
      }
      console.log(limit);
    }
    
    check(5);
    check(10);
    check(-1);
    check();
    check(null);

    【讨论】:

    • 这里的问题是linkedinInsight 既不是null 也不是undefined。该代码甚至在分配之前就会引发错误。
    • 早期的let linkedinInsight = null 怎么样?
    • 呃,backgroundPage["_linkedin_pixel_data"][tab.id].insight_tags; 还会抛出错误吗?
    • 是的,我看了看它,忘记了我把它看作是一种应对机制。
    【解决方案3】:

    这似乎适用于我的情况。

      const paths = data
        ? data.map((item) => ({
            params: { slug: item.attributes.slug },
          }))
        : [];
    

    根据我的理解,下面也可以使用(可选链接运算符(?。)和空值合并运算符(??))

      const paths =
        data?.map((item) => ({
          params: { slug: item.attributes.slug },
        })) ?? [];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-17
      • 2017-10-17
      • 2017-07-30
      • 1970-01-01
      • 1970-01-01
      • 2021-03-30
      • 2015-03-26
      • 1970-01-01
      相关资源
      最近更新 更多