繁体   English   中英

在尝试使用箭头函数返回三元运算符时,如何修复ES6 Eslint错误?

[英]How can I fix ES6 Eslint errors while trying to return a ternary operator in arrow function?

我知道() => {}不需要返回,但如果不存在则Eslint抱怨未使用的表达式。

export const isInInterval = (from, to, target) => {
  if (isNaN(Date.parse(to)) && isNaN(Date.parse(from)) === true) {
    return
  }
  const toUnixTimestamp = time => new Date(time).getTime()
  toUnixTimestamp(to) - target > toUnixTimestamp(from) ? true : false
}

下面是函数:它试图找出一些指定日期(是否to )减去指定时间内( target )后是在时间上比from 如果是这样,它应该返回true而在相反的情况下应该返回false。 我不断碰到eslint错误, expected assignment to a function call and instead saw expression

我尝试多次重写它,但在大多数迭代中我得到`箭头函数期望没有返回错误,例如:

return(toUnixTimestamp(to) - target> toUnixTimestamp(from))? 真假

我明白()=> {}不需要返回

事实并非如此。 =>后面的内容是单个表达式时,箭头函数仅隐式返回。 如果你使用=> { ,开括号{表示一个功能块的开头,你确实需要在块的末尾显式return (或者你想要return其他地方)。

目前,你的代码根本没有返回任何东西 - 这就是linting错误试图告诉你的 - true : false现在没有被使用,它只是一个孤立的表达式。

因此,只需将return语句添加到条件的开头:

export const isInInterval = (from, to, target) => {
  if (isNaN(Date.parse(to)) && isNaN(Date.parse(from)) === true) {
    return
  }
  const toUnixTimestamp = time => new Date(time).getTime()
  return toUnixTimestamp(to) - target > toUnixTimestamp(from)
    ? true
    : false
}

或者,因为>已经评估为boolean ,您可以完全省略条件运算符:

return toUnixTimestamp(to) - target > toUnixTimestamp(from)

这里是你如何写一个箭头函数, 使用隐式返回的例子:

export const isEarlyTimestamp = (timestamp) => (
  timestamp < 4000000
  ? true
  : false
);

试试这个:

export const isInInterval = (from, to, target) => {
    if (isNaN(Date.parse(to)) && isNaN(Date.parse(from)) === true) {
    return false
    }
    const toUnixTimestamp = time => new Date(time).getTime()
    return toUnixTimestamp(to) - target > toUnixTimestamp(from);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM