【发布时间】:2016-04-20 20:20:41
【问题描述】:
下面的伪代码。我的产品结果集合有一个可选的图像子数组。我要做的是在尝试访问 image.href 以用作图像源之前检查产品是否存在图像。在图像不存在的情况下,它每次都会中断。或者,我尝试了 typeof 'undefined' ,但也没有用。
if (this.products) {
//return "<i class='fa fa-gift'></i>"
console.log("has products");
if (this.products[0].images) { <--- breaks
console.log("item 0 has images");
}
if (this.products.images) { <--- breaks
console.log("has images");
}
} else {
console.log("don't have products");
}
编辑/更新
最终,我认为 Patrick Lewis 对此提供了最佳答案 - 使用混合三元运算符。类似于:
myVar = object && object.name || “富”
如果对象存在并且有名字,上面会为 myVar 分配名称值,或者......它会分配静态的“foo”。
【问题讨论】:
标签: javascript meteor collections ternary-operator