【问题标题】:Using typeof in JavaScript still causes error for undefined object在 JavaScript 中使用 typeof 仍然会导致未定义对象的错误
【发布时间】:2016-09-26 21:11:41
【问题描述】:

您好,我正在查询 Amazon API,并且时不时地有一个项目没有图像。我试图解决这个问题,但我仍然收到错误:TypeError: Cannot read property '0' of undefined

      if (typeof result.ItemSearchResponse.Items[0].Item[i].SmallImage[0].URL[0] !== undefined) {
          //items['image'][i] = result.ItemSearchResponse.Items[0].Item[i].LargeImage[0].URL[0];
          console.log(result.ItemSearchResponse.Items[0].Item[i].SmallImage[0].URL[0]);
      }

如果我注释掉 if 语句,错误就会消失 - 有没有更好的使用 typeof 的方法 - 这会导致对象属性根本不存在?或者任何人都可以就如何解决提供建议?

谢谢

【问题讨论】:

  • 这意味着results.ItemSearchResponse.Itemsresults.ItemSearchResponse.Items[0].Itemresults.ItemSearchResponse.Items[0].Item[i].SmallImageresults.ItemSearchResponse.Items[0].Item[i].SmallImage[0].URLundefined。基本上,您在某个索引处访问的任何内容都可能是undefined。独立验证它们。
  • 你需要检查Object的每一层,typeof不处理RHS内的引用错误,typeof foo; // undefined但是typeof foo.bar; // error
  • 尝试记录每个数组以获取未定义的数组 console.log(results.ItemSearchResponse.Items[0].Item) console.log(results.ItemSearchResponse.Items[0].Item[ i].SmallImage) console.log(results.ItemSearchResponse.Items[0].Item[i].SmallImage[0].UR‌​L)
  • 谢谢!是的,我刚刚检查过,其中一项缺少 URL。我想我应该将此检查添加到所有返回的属性中

标签: javascript jquery amazon-web-services typeof


【解决方案1】:

typeof 总是返回一个字符串,所以它是

if ( typeof something_to_check !== 'undefined' )

如果您检查实际的undefined,它会失败,因为undefined !== "undefined"

至于错误,这意味着您正在尝试访问未定义内容的第一个索引 ([0])

result.ItemSearchResponse.Items

result.ItemSearchResponse.Items[0].Item

result.ItemSearchResponse.Items[0].Item[i].SmallImage

result.ItemSearchResponse.Items[0].Item[i].SmallImage[0].URL

你必须检查每一个,如果你不知道哪一个失败了

if ( result.ItemSearchResponse.Items &&
     result.ItemSearchResponse.Items[0].Item &&
     result.ItemSearchResponse.Items[0].Item[i].SmallImage &&
     result.ItemSearchResponse.Items[0].Item[i].SmallImage[0].URL
   ) {
     // use 
     var img = result.ItemSearchResponse.Items[0].Item[i].SmallImage[0].URL[0]
   }

如果索引可能是错误的,或者不是数组等,您也必须检查。

【讨论】:

  • typeof window.foo.bar 不(可能)返回字符串
【解决方案2】:

为什么不使用

var arr = results.ItemSearchResponse.Items[0].Item[i].SmallImage || false;
if(arr[0]){
    // do some work
}

如果任何包含数组不存在或SmallImage 中不存在图像,则条件失败。

【讨论】:

  • 作业会抛出,因此您可能希望将其包含在 try 块中。
  • 创新的答案,节省了很多行!非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-02
  • 1970-01-01
  • 2011-09-26
  • 2011-02-06
  • 2017-02-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多