我在数组上迭代,并且在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
循环的综合。