在JavaScript中使用typeof仍然会导致未定义对象的错误

Using typeof in JavaScript still causes error for undefined object

本文关键字:未定义 对象 错误 JavaScript typeof      更新时间:2023-09-26

嗨,我正在查询亚马逊API,每隔一段时间一个项目没有图像。我试图解释这一点,但我仍然得到错误:TypeError:无法读取属性'0'的未定义

      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 -这将解释对象属性不存在吗?或者谁能给点建议如何解决?

谢谢

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]
   }

如果索引可能是错误的,或者不是一个数组等,你必须检查,以及

为什么不使用

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

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