2

(Edit: I found this syntax while reading someone else's code)

Is there any good reason for using the following syntax for setting a variable in javascript:

this.index >= this.items.length && (this.index = 0);

Is it just to get the expression on one line of code, or is there another, dare I say better, reason for this way of doing it...

Edit: The code is equivalent to:

if (this.index >= this.items.length) { 
    this.index = 0; 
}
4

3 回答 3

3

Wow, no. Just no. I consider myself a pretty good JavaScript programmer and I can't tell you what this code does.

Does it just do this.index = this.items.length or does it do something weird like this.index = false?

If you intend:

if (this.index >= this.items.length) {
    this.index = 0;
}

Then you could consider:

this.index = (this.index >= this.items.length) ? 0 : this.index;

But that doesn't really improve it, does it?

于 2013-09-25T12:22:39.673 回答
1

我认为这段代码的意图是

 this.index = this.index >= this.items.length ? this.items.length : 0;

或者

 this.index = this.index >= this.items.length ? 0 : this.items.length;

第三个可能的意图(这可能是它应该做的)。

 this.index = this.index >= this.items.length ? 0 : this.index;

但这只是最好的猜测,这条线根本没有任何意义......而且您通常不会分配这样的变量。实际上它甚至没有分配变量 this.index。

实际上,您的代码确实有效。请参阅此处的工作示例:http: //jsfiddle.net/Elak/EthsP/

在 tbh 之前从未见过这种语法,我写了很多 JavaScript ......但你永远不会停止学习新东西:p

于 2013-09-25T12:25:23.157 回答
1

不,没有充分的理由,我认为人们经常这样做,所以它是一个“单线”,你最好使用if这样的。

if( this.index >= this.items.length ) {
    this.index = 0;
}

因为正如你所看到的,人们对它的实际作用感到困惑。

但你仍然可以像这样保持它的单线

if( this.index >= this.items.length ) { this.index = 0; }
于 2013-09-25T12:29:04.203 回答