在迭代阵列咖啡脚本时检查未定义的未定义



我在数组上迭代,并且在Coffeescript中迭代时会遇到undefined可变错误。我不太确定如何在Coffeescript中迭代时检查未定义的未定义。

请在下面找到我的代码。

  i=0
  while Program.flatPercentageDiscountByMajorClass.length
    var 
    if typeof Program.flatPercentageDiscountByMajorClass[i].majorClass == 'undefined'  // this line is not working. throwing Undefined error
      FlatPercentageFlag = true
    else
      PdpTableFlag = true
    break  
    i++

用于检查咖啡脚本中的undefined元素您可以使用这样的三元运算符。

Flag = if typeof Program.flatPercentageDiscountByMajorClass[i].majorClass != 'undefined' then false else true 

我猜想Program.flatPercentageDiscountByMajorClass[i]undefined,并且尝试访问其上的majorClass属性会引起错误。

您可以使用Coffeescript中的存在操作员来避免这种情况。

if typeof Program.flatPercentageDiscountByMajorClass[i]?.majorClass == 'undefined'  
// The existential operator goes before the dot  ------^ 

其他一些观察值:

var在咖啡文字中不使用。我真的不确定您试图通过此循环实现什么。break意味着您只会执行一个迭代 - 这只是为了调试目的吗?

您应该研究循环&在库存中迭代迭代而不是使用while循环的综合。

相关内容

最新更新