【问题标题】:Meteor detecting existence of field in collection流星检测集合中存在场
【发布时间】: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


    【解决方案1】:

    可能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[0].images[0].href。检查图像时,以下测试失败。令人沮丧!
    • 好的 - 明白了 - 这基本上就是我的目标。
    【解决方案2】:

    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
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-05-03
      • 2019-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多