三元运算符在JSHint中显示错误-预期分配或函数调用,而是看到一个表达式 [英] Ternary operator displays error in JSHint - Expected an assignment or function call and instead saw an expression

查看:85
本文介绍了三元运算符在JSHint中显示错误-预期分配或函数调用,而是看到一个表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个三元运算符 dir ==='next'吗?++ $ currentSlide:-$ currentSlide; 在我的JS中用于递增整数.当我在grunt JSHint中运行脚本时,此行突出显示为预期的分配或函数调用,而是看到了一个表达式.

I have a ternary operator dir === 'next' ? ++$currentSlide : --$currentSlide; in my JS used to increment of decrement an integer. when I run my script in grunt JSHint hightlights this line as Expected an assignment or function call and instead saw an expression.

有人可以告诉我我要怎么做吗?我应该设置其他条件吗?

Can anyone advise where I'm going wrong with this? Should I set my condition up differently etc?

推荐答案

您正在将条件运算符误用作 if 语句,因此才得到该注释.代码中的实际工作是作为表达式的副作用完成的,而表达式的结果将被忽略.

You are misusing the conditional operator as an if statement, that's why you are getting that note. The real work in the code is done as a side effect of the expression, and the result of the expression is ignored.

作为真实的 if 语句,应为:

As a real if statement, it would be:

if (dir === 'next') {
  ++$currentSlide;
} else {
  --$currentSlide;
}

如果将其用作实际表达式,则可以使用条件运算符:

You can use the conditional operator if you use it as an actual expression:

$currentSlide += dir === 'next' ? 1 : -1;

这篇关于三元运算符在JSHint中显示错误-预期分配或函数调用,而是看到一个表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆