为什么我的使用字符串插值的函数根据以下代码给我两个不同的错误。 Javascript

问题描述 投票:0回答:1

我确实通过定义一个单独的局部变量来存储返回的函数值来弄清楚如何使代码正常工作。我只是很好奇为什么基于以下代码使用$ {total}会导致两个不同的字符串。

以下代码将函数主体插入到字符串中。

if (typeof cardNumber === 'undefined') {
 return "Sorry, we don't have a credit card on file for you."
} else {
   let cartTotal = total();
   cart = []
   return `Your total cost is $${total}, which will be charged to the card ${cardNumber}.`
 }
}```

**The following code interoplates the returned value of the total function and uses that value in the string it also throws a Type error that total is not a function** 

 ```function placeOrder(cardNumber) {
   if (typeof cardNumber === 'undefined') {
     return "Sorry, we don't have a credit card on file for you."
   } else {
       total = total();
       cart = []
       return `Your total cost is $${total}, which will be charged to the card ${cardNumber}.`
     }
   }  ```



javascript string-interpolation function-call
1个回答
0
投票

已解决。在第二个示例中,我用返回的值覆盖了total()函数,这使我可以一次获得正确的答案。在第一个代码中,我没有覆盖函数,当我对其进行插值时,我得到了函数主体。

© www.soinside.com 2019 - 2024. All rights reserved.