javascript - 在 JavaScript 中使用 typeof 仍然会导致 undefined object 的错误

标签 javascript jquery amazon-web-services typeof

您好,我正在查询 Amazon 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]
   }

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

关于javascript - 在 JavaScript 中使用 typeof 仍然会导致 undefined object 的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39712463/

相关文章:

amazon-web-services - 启用 Lambda@Edge 后调试 CloudFront 的问题

javascript - 点击操作按钮的那一刻

PHP:加载 gzip 压缩的 javascript 文件

javascript - 使用jquery同时更改情侣网站上的文本字符串

javascript - 更改全局变量的 html 界面

javascript - 无法将 jQuery object.method 传递给另一个要执行的函数

amazon-web-services - AWS Lambda 和 Pusher 集成。如何发送通知?

javascript - Express:将参数分配给 app.use() 的不同方法

javascript - 单元测试 : Number. toLocaleString()

java - 如何在 AWS Elastic Beanstalk 上安装/运行 Spark Java 框架?