下面是伪代码。我的产品结果集合有一个可选的图像子数组。我想做的是在尝试访问 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");
}
编辑/更新
最终,我认为帕特里克·刘易斯为此提供了最佳答案 - 使用混合三元运算符。就像:
myVar = 对象 && 对象.name || “富”
如果对象存在并且有名称,上面将为 myVar 分配名称值,或者...它将分配静态“foo”。
最佳答案
可能this.products
是一个空数组。尝试:
if (this.products && this.products.length) {
var images = this.products[0].images;
if (images && images.length) {
console.log("item 0 has images");
} else {
console.log("item 0 does not have images");
}
} else {
console.log("don't have products");
}
关于javascript - meteor 检测集合中字段的存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33873101/