在迭代之前是否有更简洁的方法来检查对象的存在?

时间:2015-10-19 20:24:13

标签: coffeescript

我们说我有两个对象:

coffee> objA = {a: 4, b: [1,2,3,4], c: [5,6,7]}
{ a: 4, b: [ 1, 2, 3, 4 ], c: [ 5, 6, 7 ] }
coffee> objB = { a: 4, b: [ 1, 2, 3, 4 ] }
{ a: 4, b: [ 1, 2, 3, 4 ] }

我想通过相同的循环运行它们:

do (obj) -> 
  for n in obj.b
    do (b) -> 
      ... stuff here 
  for n in obj.c
    do (c) -> 
      ... stuff here 

c可能不存在,所以我在前面添加if

do (obj) -> 
  for n in obj.b
    do (b) -> 
      ... stuff here 
  if obj.c?   
    for n in obj.c
      do (c) -> 
        ... stuff here 

这让我想知道是否有更好的方法来处理if obj.c?。我认为when会处理它,但是在分配循环对象后评估when,导致TypeError: Cannot read property 'length' of undefined

1 个答案:

答案 0 :(得分:3)

您可以使用问号的零替代形式:

objB = { a: 4, b: [ 1, 2, 3, 4 ] }
for n in objB.c ? []
    console.debug("Hi there #{n}")
相关问题