【问题标题】:How to store a function into a variable in JS如何将函数存储到JS中的变量中
【发布时间】: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/*... */ ?? 0totalV.filter/*... */ || 0 的后备(取决于你需要什么 When should I use ?? (nullish coalescing) vs || (logical OR)?

标签: javascript


【解决方案1】:

为什么不

const complexArrayFunc = (array) => {
  if (!array) return []
  return array.filter((nan) => nan)
    .reduce((a, b) => a + b, 0)
    .toFixed(2)

【讨论】:

    【解决方案2】:

    您可以使用 lambdas(匿名函数/箭头函数表达式):

    例如:

    const repeatableCode = (totalV) => {
        return totalV
            .filter((nan) => nan)
            .reduce((a, b) => a + b, 0)
            .toFixed(2)
    }
    

    了解更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-25
      • 2021-11-28
      相关资源
      最近更新 更多