Why does jshint not recognize an assignment as an expression?

耗尽温柔 提交于 2019-11-30 08:13:49

If you really want to listen to JSHint, convert the expression to a boolean by:

while (!!(bookmark_element=bookmark_list[iterator++]))

! means: Something that evaluates to true is converted to false,
         something that evaluates to false is converted to true.

So, !! means: Convert something to the conditional representation.

Dave Newton
/*jshint boss:true */

Experiment with the options.

I'm sure that jshint understands the expression fine, it is just that most people who write if (a = b) actually meant if (a == b) and so this generates a warning.

Since your code is what you intended you could add an explicit test:

while ((element_iterator = element_iterator.nextSibling) !== null) { ... }

There are at least two ways to solve the reported error, according to JSHint docs.

  1. Add /*jshint boss:true */ before conditional statement
  2. Wrap statement in extra parentheses, i.e. while ((element_iterator = element_iterator.nextSibling)) {...}

Personally, I think surrounding with extra parentheses is best practice since it keeps the error check but still makes good sense code-wise. Adding the !! before does actually nothing but convert the expression to true/false back and forth two extra times.

It is an expression, and you can modify it to work with JSHint (although it's not nice) like so:

while(element_iterator.nextSibling) {
    element_iterator = element_iterator.nextSibling;

For your last example. However, you don't need to do this. JSHint is only a tool to help you improve coding habits and correct mistakes, but given that what you have is clear, concise, and (in my opinion) the best way of doing it - just ignore those messages.

jshint can't tell if you really meant to make an assignment in the condition block, or if that was really supposed to be a comparison. The concern would be that other humans might have the same doubt.

In the case of an iterator, I think you're okay.

I had this error because I had a trailing comma in a declaration preceding the function:

this.foo = "bar",   // <- Error was here

this.myfunc = function() {
   ...   // <- Error reported on this line
};

(It was hard to find, but reinforces my opinion that linters are usually right, it's my code that's wrong. If I had disabled the warnings globally - or even in that spot - the bug still would have been present.</lecture>)

Add /* jshint expr: true */ comment in your Javascript file, it will not show warning anymore.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!