【问题标题】:Javascript ternary operator where a result can be a string and function [duplicate]Javascript三元运算符,其中结果可以是字符串和函数[重复]
【发布时间】:2021-09-10 18:04:35
【问题描述】:

全部,

我想要实现的是类似于下面的东西,但我不确定它是否可能。如果该值等于文件长度,我想将字符串更新为done,但也要在完成时调用一个函数。我认为这不是放置函数调用的最佳位置,但很想知道这是否可能以及是否是好的做法。

   {{ value == files.length ? 'Done'; resetFileInput() : 'Pending' }}

【问题讨论】:

  • 看到你有大括号,我假设这是在模板中完成的?根据您使用的框架/库,您可能最好使用计算的或类似的。
  • 为什么不直接使用if - 你正在滥用三元运算符来尝试这样做
  • 谢谢 Terry - 没错,它在模板中。
  • 如果你可以调用一个函数,你可以只创建一个返回正确字符串的函数并调用你想要的任何东西,然后执行{{ myFunction(value, files) }}或传递你想要的任何东西。
  • 这能回答你的问题吗? How to I execute multiple functions on the result of a ternary operation? 最佳答案说这不是好的做法

标签: javascript conditional-operator


【解决方案1】:

您应该将逻辑提取到一个新函数中,而不是让代码更难阅读和维护:

function myFunction(value, files) {
    if (value == files.length) {
        resetFileInput();
        return 'Done';
    }
    return 'Pending';
}

然后从模板中调用:

{{ myFunction(value, files) }}

这样你就不会把太多的逻辑放在你的视图中。

【讨论】:

    【解决方案2】:

    您可以在逗号分隔的列表中拥有任意数量的值(使用())。所有函数都将运行,列表的最后一个将被“返回”。

    true:

    console.log(true ? (alert("hi"), 'Done') : 'Pending')

    false:

    console.log(false ? (alert("hi"), 'Done') : 'Pending')

    【讨论】:

      【解决方案3】:

      你可以这样做:

      const resetFileInput = () => {
          console.log("Reset file input")
      }
       
      const done = () => {
        resetFileInput()
        return "done"
      }
      
      let files = ["file"]
      let value = files.length ? done() : "Pending"
      
      console.log(value)

      【讨论】:

        猜你喜欢
        • 2018-11-27
        • 2016-06-26
        • 2015-06-09
        • 2018-06-11
        • 1970-01-01
        • 2015-09-21
        • 1970-01-01
        • 2021-10-06
        • 2020-03-24
        相关资源
        最近更新 更多