Meteor正在检测集合中是否存在字段
Meteor detecting existence of field in collection
下面的伪代码。我的产品结果集合有一个可选的图像子阵列。我想做的是在尝试访问image.href用作图像源之前,检查产品是否存在图像。在图像不存在的情况下,它每次都会中断。另外,我也尝试过"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=对象&;对象名称||"foo"
如果对象存在并且它有一个名称,或者。。。它将分配静态"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");
}
this.products是您的集合还是像MyColl.find()这样的查询的结果?
如果这是查询的结果,你可以这样做:
if (typeof this.products == "object") {
if (typeof this.products.images == "object") { // if images is a property of products and images is an array
// od what you want here
}
}
相关文章:
- 用于检查数组中是否存在元素的javascript自定义方法
- 是否存在React Native“;WEB代码安全防护”;
- 验证会话中是否存在对象's数组
- 如何查找值是否存在于二叉树中
- 检查是否存在使用chrome扩展的javascript库
- 是否存在Javascript Liferay Service库的文档?如何处理错误情况
- 测试mongo脚本中是否存在参数
- 检查搜索结果是否存在多次如果是,则在Javascript中只显示一个结果
- 检查数组中是否存在字符串值,并返回找到的数组值js
- 如何通过json对象选项卡中的Id来检查对象是否存在
- 检查是否存在任意控制器/操作
- Javascript滑块不滑动,如何判断是否存在JS冲突
- 根据手机上是否存在文件,在jQuery mobile中动态填充列表视图
- javascript测试是否存在两个标志中的任何一个
- 如何使用javascript检查移动sd卡中是否存在文件
- 当提供函数名称时,检查函数是否存在于同一作用域中
- 需要帮助使用JQuery.inArray()检查值是否存在
- 确定元素是否存在
- 使用javascript检查服务器上是否存在html文件
- 是否存在类似ExtJS 4的框架;正常的“;网站