检查json对象是否未定义

5

我正在使用亚马逊产品API,我的请求返回XML格式的数据,我将其编码为JSON格式。

我的信息流中有些物品没有价格,因此我会收到以下错误提示:

TypeError: this.ItemAttributes.ListPrice is undefined

然而,我可以获取销售价格。因此,我想基本上查看是否未定义this.ItemAttributes.ListPrice,如果是,则查找this.Offers.OfferListing.Price.FormattedPrice

我该如何在jQuery中做到这一点?

我尝试了以下代码:

if (this.ItemAttributes.ListPrice != null){
var price = this.ItemAttributes.ListPrice;
}else{
var price = this.Offers.OfferListing.Price.FormattedPrice
}
4个回答

10

几乎正确。您想要检查的是undefined,而不是null

可能的一种方法是:

var price;
if (this.ItemAttributes.ListPrice !== undefined) {
    price = this.ItemAttributes.ListPrice;
}
else {
    price = this.Offers.OfferListing.Price.FormattedPrice;
}
如果您想要覆盖所有falsy值(null,undefined,zero ...),您只需将第一行更改为:
if (this.ItemAttributes.ListPrice) {
   ...

有关falsy值的更多信息在此处

您可以使用||或?运算符更简洁地编写它,但请确保保持可读性。


1
如果您正在检查多个值,编写一个函数来检查该值并返回其值(如果不是undefined或null),或者返回false可能更容易些。
var checkObj = function(obj) {
    if(obj != null || obj != undefined) {
        return obj;
    } else {
        return "Unavailable";
    }
};

0
如果这些价格中至少有一个被设置了,那么这个应该可以工作。
var price = this.ItemAttributes.ListPrice ? this.ItemAttributes.ListPrice : this.Offers.OfferListing.Price.FormattedPrice;

0
if (this.ItemAttributes.ListPrice != null || this.ItemAttributes.ListPrice != undefined){
var price = this.ItemAttributes.ListPrice;
}else{
var price = this.Offers.OfferListing.Price.FormattedPrice
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接