【问题标题】:Cannot convert undefined or null to object js无法将 undefined 或 null 转换为对象 js
【发布时间】:2020-07-19 02:24:22
【问题描述】:

我使用的是静态 .js 文件,只要所有键都有值,这段代码就可以工作。我想从一个网址输入数据。但是,我对“未定义”和“空”值的错误处理一直没有成功。控制台中的错误为:

main.js:14 未捕获的类型错误:无法在 SVGPathElement 的 Function.entries () 处将 undefined 或 null 转换为对象。 (main.js:14) 在 SVGPathElement.handle (jquery-2.2.4.min.js:3) 在 SVGPathElement.dispatch (jquery-2.2.4.min.js:3) 在 SVGPathElement.r.handle (jquery- 2.2.4.min.js:3)

下面是 main.js 代码没有错误处理。我一直在阅读并尝试实施有关此主题的一些建议。但是,没有任何工作。我的尝试之一是下面的第二个代码框。任何建议,将不胜感激。


        $("path, circle").hover(function(e) {
          // make tooltip visible
          $('#info-box').css('display','block');
          // get year from selector element
          const year = document.querySelector('#myList').value;
          // filter the `data` array for states just in that year
          const filtered = data.filter(d => d.Year == year);
          // filter states of that year to just the one state matching the id of 
          // the path that is being hovered on 
          const state = filtered.filter(d => d.id == $(this).attr('id'))[0];
          // create the html string to populate the tooltip with 
          // as long as the key isn't 'id' then continue building
          let state_html = '';
          Object.entries(state).forEach(([key, value]) => {
            if (key != 'id') {
            state_html += `${key}: ${value}<br>`;
            }
          })
          // change value of tooltip to html we just made
          $('#info-box').html(state_html);
        });
        $("path, circle").mouseleave(function(e) {
          $('#info-box').css('display','none');
        });
        $(document).mousemove(function(e) {
          $('#info-box').css('top',e.pageY-$('#info-box').height()-30);
          $('#info-box').css('left',e.pageX-($('#info-box').width())/2);
        }).mouseover();
        var ios = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
        if(ios) {
          $('a').on('click touchend', function() {
            var link = $(this).attr('href');
            window.open(link,'_blank');
            return false;
          });
        }
        function getOption() {
          const selectElement = document.querySelector('#myList');
          output = selectElement.value;
          document.querySelector('.output').textContent = output;
        }

    $("path, polyline, polygon").hover(function(e) {
      // make tooltip visible
      $('#info-box').css('display','block');
      // get date from selector element
      const Date = document.querySelector('#myList').value;
      // filter the `data` array for counties just in that date
      const filtered = data.filter(d => d.date == Date);
      // filter counties of that date to just the one county matching the id of 
      // the path that is being hovered on 
      const county = filtered.filter(d => d.id == $(this).attr('id'))[0];
      // create the html string to populate the tooltip with 
      // as long as the key isn't 'id' then continue building
      let county_html = '';
      Object.entries(undefined).forEach(([key]) => {
      if (key != 'undefined' | 'null') {
        county_html += `$(0): $(0)<br>`;
        }
      })
      Object.entries(county).forEach(([key, value]) => {
        if (key != 'id') {
          county_html += `${key}: ${value}<br>`;
        }
      })
      // change value of tooltip to html we just made
      $('#info-box').html(county_html);
    });
    $("path, polyline, polygon").mouseleave(function(e) {
      $('#info-box').css('display','none');
    });
    $(document).mousemove(function(e) {
      $('#info-box').css('top',e.pageY-$('#info-box').height()-30);
      $('#info-box').css('left',e.pageX-($('#info-box').width())/2);
    }).mouseover();
    var ios = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
    if(ios) {
      $('a').on('click touchend', function() {
        var link = $(this).attr('href');
        window.open(link,'_blank');
        return false;
      });
    }
    function getOption() {
      const selectElement = document.querySelector('#myList');
      output = selectElement.value;
      document.querySelector('.output').textContent = output;
    }

```

【问题讨论】:

  • 为什么要将 undefined 转换为 Object 能解释一下吗?
  • 我有一组对象,这些对象被用户输入过滤并在鼠标悬停(悬停)时显示。代码是动态的,显示过滤数据的键:值。我拥有的静态数据是干净的。但是,我要使用的实时数据缺少值。缺少的值会引发错误并导致程序在悬停时停止并且无法工作。使用 Davidmwhynot 建议的代码,程序不再中断。它保存最后一个悬停在项目上的键:值,直到下一个对象悬停。

标签: javascript jquery html arrays


【解决方案1】:

第二个文件第 14 行的循环是您的错误的根源,并且可能可以被删除(因为我没有看到您想要迭代的任何其他对象):

      // this block can likely be removed
      Object.entries(undefined).forEach(([key]) => {
        if (key != 'undefined' | 'null') {
          county_html += `$(0): $(0)<br>`;
        }
      })

相反,您似乎想检查您的county 对象是否有未定义或空值。这可以在你不需要的循环中完成:

Object.entries(county).forEach(([key, value]) => {
  if (key !== 'id' && key !== undefined && key !== null) {
    county_html += `${key}: ${value}<br>`;
  }
});

【讨论】:

  • 同样的错误。虽然,您的代码看起来很有前途。我要玩一会儿。如果我发现了什么,请告诉你。感谢您的快速回复。
  • 我相信我的问题超出了错误处理代码的范围。我正在为我的 data.js 文件读取数据。当以 csv 格式读入时,它是控制台记录数据。但是,我相信当我尝试将其转换为 json 时会出现脱节。
  • ' const url = "raw.githubusercontent.com/nytimes/covid-19-data/master/…";常量数据 = d3.csv(url, 函数(数据){ }); '
  • function csvJSON(data){ var lines=url.split("\n"); var headers=lines[0].split(","); for(var i=1;i&lt;lines.length;i++){ var obj = {}; var currentline=lines[i].split(","); for(var j=0;j&lt;headers.length;j++){ obj[headers[j]] = currentline[j]; } data.push(obj); } return JSON.stringify(data); }
  • 是的。我去了我原来的静态 data.js 文件并删除了一些数据行。您的错误处理代码有效!我将需要重新访问我的 csv 到 json 代码以找到中断。谢谢。
猜你喜欢
  • 2021-07-29
  • 2020-12-06
  • 1970-01-01
  • 1970-01-01
  • 2022-06-22
  • 2023-02-06
  • 2021-12-07
  • 2020-08-15
  • 1970-01-01
相关资源
最近更新 更多