检查CoffeeScript中嵌套for循环中的数组是否为null

时间:2014-07-22 14:14:46

标签: coffeescript

请考虑以下代码:

class StoreController
    constructor: ->
      @products = gems

      current_id = 0
      for product in @products
        if product.images?
          for img in product.images
            img.id = current_id
            current_id += 1


gems = [
  {
    name: 'Dodecahedron'
    images: [
        {
            full: "assets/img0.gif"
        }
        {
            full: "assets/img1.gif"
        }
    ]
  }
  {
    name: 'Gemmy Gem'
  }
  {
    name: 'Pentagonal Gem'
  }
]

有没有更好的方法来编写嵌套for循环来检查没有product.images?行的if product.images?

修改 下面接受的答案确实回答了这个问题。但是,我决定改变我编写代码的方式来改为使用自定义过滤器。

filter.js.coffee中,我写了以下内容:

filterMod = angular.module 'storeFilters', []
current_id = 0

filterMod.filter 'addIds', ->
  return (items) ->
    # avoid $rootScope:infdig
    return items if !items? || items.processed

    for img in items
      img.id = current_id
      current_id += 1

    items.processed = true
    return items

HTML如下所示,请注意在内部addIds

中使用ng-repeat
<div ng-controller="StoreController as store">
  <ul ng-repeat="product in store.products" class="list-group">
    <li class="list-group-item">
        <h3> {{product.name}} <em class="pull-right">{{product.price | currency }}</em></h3>
        <div class="gallery">
          <div ng-repeat="img in product.images | addIds ">
            {{img.id}}
            <img ng-src="{{img.full}}"/>
          </div>
        </div>
        <p>  {{product.description}}</p>
        <button ng-show="product.canPurchase">Add to Cart</button>
    </li>
  </ul>
</div>

为了完整起见,这里有app.js.coffee

app = angular.module 'store', ['storeFilters']

app.controller 'StoreController',
  class StoreController
    constructor: ->
      @products = gems

gems = []

3 个答案:

答案 0 :(得分:2)

您可以在循环中使用when条件:

for product in @products when product.images?
  for img in product.images
    img.id = current_id
    current_id += 1

答案 1 :(得分:0)

您需要检查product.images是否为null,就像现在循环一样,否则您将出错。 example here显示了我在说什么。

干杯!

答案 2 :(得分:0)

我不确定你当前的ID是什么样的(从随机数开始或从0到图像的长度),但你可以在for循环中抓取索引这样做:

for product in @products when product.images?
  img.id = current_id + i for img, i in product.images

或者只是它的索引:

for product in @products when product.images?
  img.id = i for img, i in product.images

或冷静:

img.id = i for img, i in product.images for product in @products when product.images?