我的代码中有这一行:
de: (_.max(data, (product) -> product.prices.de )).price.de
我想首先检查product.prices
是否已定义,如果已定义,则返回product.prices.de
,否则返回0。
在 javascript 中我会写这样的东西:
angular.isDefined(product.prices) ? product.prices.de : 0
但是当我在coffeescript中尝试同样的事情时,coffeelinter不接受它。有什么提示吗? CoffeeScript 和 JavaScript 在查询运算符的使用上有区别吗?
编辑:
我可以写
de: (_.max(data, (product) -> product.prices?.de )).prices.de
但在这种情况下,如果 product.prices
不存在,该函数将返回 null 而不是 0
最佳答案
CoffeeScript 中的三元运算符只是一个 if 条件,因为 CoffeeScript 中的所有内容都是表达式。所以如下:
condition ? something : somethingElse
变成:
if condition then something else somethingElse
请注意,在您的情况下,您不会写:
if product.prices then product.prices.de else 0
您可能想要:
product.prices?.de or 0
关于javascript - CoffeeScript 和 JavaScript 中三元(问号运算符)之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27591901/