简体   繁体   中英

Using typeof in JavaScript still causes error for undefined object

Hi i'm querying Amazon API and every now and again an item doesn't have an image. I'm trying to account for this but i still get the error: 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 i comment out the if statement the error disappears - is there a better way to use typeof - which would account for the object property not existing at all? Or can anyone give advise on how to solve?

Thanks

typeof always returns a string, so it's

if ( typeof something_to_check !== 'undefined' )

If you check for the actual undefined it fails, as undefined !== "undefined"

As for the error, it means you're trying to access the first index ( [0] ) of something that isn't defined, either

result.ItemSearchResponse.Items

or

result.ItemSearchResponse.Items[0].Item

or

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

or

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

you have to check each one, if you don't know which one fails

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

If the indices can be wrong, or not an array etc. you have to check for that as well.

Why not use

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

Since the condition fails if any of the containing arrays do not exist or if no image exists in SmallImage .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM