【问题标题】:Whats the role of this && operator in this code? [duplicate]这个 && 运算符在这段代码中的作用是什么? [复制]
【发布时间】:2019-10-10 04:09:31
【问题描述】:

我的代码在这部分失败了..我无法理解这个 && 运算符在 js 中的作用是什么?

    export function calculateLineTotals(line, invoice) {

    let totals = _calculateLineTotals(line, invoice)
    return {
    amount: totals.amount && 
        totals.amount.decimalPlaces(2).toNumber(),
    vatRate: totals.vatRate && 
        totals.vatRate.decimalPlaces(2).toNumber(),
    grossAmount: totals.grossAmount && 
        totals.grossAmount.decimalPlaces(2).toNumber(),
    vatAmount: totals.vatAmount && 
        totals.vatAmount.decimalPlaces(2).toNumber(),
    }

【问题讨论】:

  • 阅读有关 logical operators 的 JavaScript 文档。
  • “我的代码在这里失败了” - 你能更具体地说明它是如何失败的吗?您的浏览器控制台中有错误消息吗?
  • 你可以读成这样:if totals.amount is truthy,那么我希望它得到totals.amount.decimalPlaces(2).toNumber(),否则它将是undefined

标签: javascript


【解决方案1】:
totals.amount && totals.amount.decimalPlaces(2).toNumber()

totals.amount 将评估为值

&& 将在左侧计算结果为真时计算右侧表达式(不是 nullundefined0

我想这就是你想知道的

这消除了cant evaluate 'decimalPlaces' of undefined 错误的可能性

【讨论】:

  • 太棒了……这就是我想知道的
猜你喜欢
  • 2011-03-08
  • 2016-06-17
  • 2015-07-07
  • 2015-01-22
  • 2011-09-28
  • 1970-01-01
  • 2015-10-15
  • 2013-07-30
  • 1970-01-01
相关资源
最近更新 更多