开发者问题收集

通过 json 中的键访问值会引发未定义

2018-06-13
63

您好,我遇到了一个奇怪的错误,我有一个下面的对象

let dataFromUrl =  {
      "careerTrackId": 510,
       "country": [],
       "geography": [18],
       "ou2": [51549564],
       "ou3": [],
       "ou4": [],
       "ou5": [],
       "ou6": [],
       "ou7": [],
       "ou8": [],
       "region": []
    } 

console.log(dataFromUrl.geography.length);


// Here in this method iam using this dataFromUrl

   

     function getGeoUnitId(dataFromUrl) {
    console.log("dataFromUrl",dataFromUrl);
  console.log("dataFromUrl.geography",dataFromUrl.geography);
  console.log("dataFromUrl.ou2",dataFromUrl.ou2);
  console.log("dataFromUrl.careerTrackId",dataFromUrl.careerTrackId);
      let geoUnitId = "(" + dataFromUrl.geography + ")";
      let str2 = "geounitid IN " + geoUnitId;
      if (dataFromUrl.geography.length == 0) {
        str2 = "";
      }
      return str2;
    }

但是当我尝试在 nodejs 代码中使用 dataFromUrl.geography.length 时,我收到以下错误:

[ 'TypeError: Cannot read property 'length' of undefined']

当我的目标是 es5 时,此代码正在运行,但是当我将目标更改为 es6 时,它就开始中断。有人知道为什么会突然发生这种情况吗?

2个回答

阅读完评论后,我可能的猜测是您正在调用不带参数的 getGeoUnitId() ,并且它使用了您可能已更改的在外部定义的 getGeoUnitId

尝试重命名参数变量名

function getGeoUnitId(somethingOtherThan_dataFromUrl) {

提示:如果您在理解 JS 代码时遇到问题,您应该使用 Chrome(或任何其他浏览器)的开发人员工具并添加调试器来查看代码流程、如何为变量分配值、在哪里更新变量等等...

Rahul Gandhi
2018-06-13

最后,我终于可以修复它了,虽然我还是不知道为什么,但是这个方法有效: JSON.parse() 解决了这个问题。

let dataFromUrl =  {
      "careerTrackId": 510,
       "country": [],
       "geography": [18],
       "ou2": [51549564],
       "ou3": [],
       "ou4": [],
       "ou5": [],
       "ou6": [],
       "ou7": [],
       "ou8": [],
       "region": []
    } 


  function getGeoUnitId(dataFromUrl) {
    console.log("dataFromUrl",dataFromUrl);
  console.log("dataFromUrl.geography",dataFromUrl.geography);
  console.log("dataFromUrl.ou2",dataFromUrl.ou2);
  console.log("dataFromUrl.careerTrackId",dataFromUrl.careerTrackId);
      let geoUnitId = "(" + dataFromUrl.geography + ")";
      let str2 = "geounitid IN " + geoUnitId;
      if (dataFromUrl.geography.length == 0) {
        str2 = "";
      }
      return str2;
    }

 dataFromUrl = JSON.parse(dataFromUrl );
 console.log(dataFromUrl.geography.length); // this started giving me 1
user3205921
2018-06-14