【发布时间】:2022-11-11 23:32:42
【问题描述】:
我一遍又一遍地重复相同的功能。我想把它合二为一,这样我就可以调用它而不必编写长代码。
totalV
.filter((nan) => nan)
.reduce((a, b) => a + b, 0)
.toFixed(2)
基本上,我想将它保存到 const 或其他东西中......然后在需要时调用它 我试图做这样的事情:
const Vol =
.filter((nan) => nan)
.reduce((a, b) => a + b, 0)
.toFixed(2)
但不幸的是我不能这样做,因为它要求“表达式”或数组来执行这个功能(在 EXPRESSION.filter.reduce 之前的东西)
编辑:更多信息
{
totalV.filter((nan) => nan)
.reduce((a, b) => a + b, 0)
.toFixed(2) == 0.0
? 0
:
totalV.filter((nan) => nan)
.reduce((a, b) => a + b, 0)
.toFixed(2)}
所以我有我在几个地方写的这个条件渲染..但是totalV可以改变,但其余代码是相同的..所以我想将不断重复的代码存储到一个变量或类似的东西中
const repeatableCode =
.filter((nan) => nan)
.reduce((a, b) => a + b, 0)
.toFixed(2)
但它拒绝在没有提前提供数组/对象的情况下工作
【问题讨论】:
-
您能否就如何调用此逻辑以及
totalV的值/可能是什么提供更多上下文。看来您可以将逻辑提取到函数中并在需要时调用它。 -
const doSomething = array => array.filter().reduce().toFixed(); -
const App= (a, b) => {} 和 ab 可以是可变的
-
Vol = totalV => totalV.filter((nan) => nan).reduce((a, b) => a + b, 0).toFixed(2)甚至更老的风格function(totalV) { return totalV.filter/*... */ }只需制作一个带有常规参数的常规函数并定期使用它。无需尝试找到一些奇怪的方法来保留方法链以附加到其他地方 -
有了更多信息:为什么不将该表达式的结果存储在变量中?
result = totalV.filter/*... */ ; result ? 0 : result或者你甚至可以使用totalV.filter/*... */ ?? 0或totalV.filter/*... */ || 0的后备(取决于你需要什么 When should I use ?? (nullish coalescing) vs || (logical OR)?)
标签: javascript