最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Ternary operator displays error in JSHint - Expected an assignment or function call and instead saw an expression -

programmeradmin0浏览0评论

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?

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?

Share Improve this question asked Aug 5, 2013 at 13:55 stylerstyler 16.5k25 gold badges85 silver badges139 bronze badges
Add a comment  | 

5 Answers 5

Reset to default 21

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.

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;

In general, for disabling the 'Expected an assignment or function call and instead saw an expression.' warning, you can do /* jshint expr: true */

Does it pass if you write it like this?

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

Linters and hinters usually don't like in/decrements because they're sensitive to bugs.

Try this syntax:

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

make ternary operator in to if else condition

Before:

(pbook.id === book.id ? book.shelf = pbook.shelf : "none");

After:

                     if(pbook.id === book.id){
                        return book.shelf = pbook.shelf
                      } else {
                        return "none"
                      };

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论