Bri*_*nka 3 javascript ternary-operator ecmascript-6 eslint
我明白() => {}不需要返回,但是如果它不存在则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
}
Run Code Online (Sandbox Code Playgroud)
这是函数:它试图找出某个指定的date(to)减去指定的period(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
}
Run Code Online (Sandbox Code Playgroud)
或者,因为已经>评估为a boolean,您可以完全省略条件运算符:
return toUnixTimestamp(to) - target > toUnixTimestamp(from)
Run Code Online (Sandbox Code Playgroud)
这里是你如何写一个箭头功能,这样的例子确实使用隐含回报:
export const isEarlyTimestamp = (timestamp) => (
timestamp < 4000000
? true
: false
);
Run Code Online (Sandbox Code Playgroud)