Javascript:如何处理未定义的参数

Javascript:如何处理未定义的参数,javascript,node.js,twitter,Javascript,Node.js,Twitter,我正在使用twitterapi来获取关于tweet的信息。我的代码正在使用此信息。有时会发生这样的情况,即api提供了一个“未定义的”,而我的代码停止了 我的想法是检查参数,只与那些正常的人一起工作: if ( typeof data.id_str.user.name === 'undefined' || data.id_str.user.name === null ){ next(); } else{ return data.id_str.user.name; } 但是我的支

我正在使用twitterapi来获取关于tweet的信息。我的代码正在使用此信息。有时会发生这样的情况,即api提供了一个“未定义的”,而我的代码停止了

我的想法是检查参数,只与那些正常的人一起工作:

if ( typeof data.id_str.user.name === 'undefined' || data.id_str.user.name === null ){ 
  next(); 
} else{
    return data.id_str.user.name;
}
但是我的支票不重要。如果我执行代码,类型错误有时仍然会发生:“无法读取未定义的属性‘name’”。你知道我能做些什么来处理这个错误并检查下一条推文吗

数据未定义。但我不知道,什么时候才能定义数据。我需要一种方法来跳过数据并使用下一个定义的数据

我已经执行了你的建议。if条件的else部分现在出现错误。为什么?它是如何工作的

if ( typeof data && data.id_str && data.id_str.user && data.id_str.user.name === 'undefined' || data && data.id_str && data.id_str.user && data.id_str.user.name === null ){
              console.log('data.id_str.user.name is undefined. --> Why?');              
            } else {
              console.log('on User  : '+data.id_str.user.name);
              }

你可以使用“保护”。执行如下操作:
typeof data&&data.id\u str&&data.id\u str.user&&data.id\u str.user.name==“未定义”
简单的解决方案,但有助于不锁定代码


编辑:在这里,我找到了更详细的防止未定义的示例:

在这种情况下,
数据链的任何部分都可能未定义,例如,
数据。id\u str
可能未定义或
数据。id\u str.user
可能未定义。后一种情况将导致:

无法读取未定义的属性“name”


有几种方法可以处理此问题,例如检查链中的每个片段
data&&data.id\u str&&data.id\u str.user
,或者将检索包装在
try
/
catch

中。错误表明未定义
user
。检查
data.id\u str.user
是否未定义,而不是
data.id\u str.user.name
。我知道data.id\u str.user.name中的某些内容未定义。我需要知道,哪个部分是未定义的?我只想检查一下,里面有没有未定义的东西。在这种情况下,我想转到下一条tweet。@在这种情况下,使用
try
/
catch
可能是最简单的解决方案thx,Pawel。我需要知道,哪个部分是未定义的?我只想检查里面有没有未定义的东西。在这种情况下,我想转到下一条tweet,检查它,在最好的情况下使用输出。在这种解决方案中,您不需要知道,只要您防止从数据对象到名称参数的未定义。如您所见&&它要求每个元素都不能未定义。在我看来,您可以避免您的比较,只要执行
如果(data&&data.id\u str&&data.id\u str.user&&data.id\u str.user.name)返回data.id\u str.user.name
它只是部分工作。错误现在会在另一行代码中显示。奇怪的是,如果代码的其他部分被执行了,那就不应该了。我想你必须重构你的代码,然后仔细检查你的程序的进程。您可以使用webstorm进行调试(调试效果非常好)。或者,如果您不怕控制台,请转到节点调试。