嘿,伙计们,我正在调试一个非常小的java脚本插件,我似乎已经弄清楚了其中的大部分,但是我在理解以下功能时遇到了一些困难:
CBPFWTabs.prototype._show = function( idx ) {
if( this.current >= 0 ) {
this.tabs[ this.current ].className = '';
this.items[ this.current ].className = '';
}
// change current
this.current = idx != undefined ? idx : this.options.start >= 0 && this.options.start < this.items.length ? this.options.start : 0;
this.tabs[ this.current ].className = 'tab-current';
this.items[ this.current ].className = 'content-current';
};我开始在函数的每一部分中运行,并将这些片段组合在一起。最后,我非常成功,MDN的优秀文档也有所帮助,但是,我仍然很难理解下面的内容:
this.current = idx != undefined ? idx : this.options.start >= 0 && this.options.start < this.items.length ? this.options.start : 0;三元运算符和逻辑运算符的结合似乎真的令人困惑,为了简化上面的操作,我试着用通俗易懂的英语阅读它,我最好的解释是:
如果idx是,不等于与未定义,而等于,则是this.current。我被困在这上面了,接下来会发生什么我都猜不出来。如果有人能用英文来解释这句话,那就太好了!
编辑:::我刚刚在评论中看到了一个很好的文章链接,所以我只想澄清一下,考虑到下面的代码行(一个嵌套的三元操作符):
int i = 5;
string result = i % 2 == 0 ? "a" : i % 3 == 0 ? "b" : i % 5 == 0 ? "c" : i % 7 == 0 ? "d" : "e"; 最后,e的功能更像是开关情况下的默认情况,对吗?谢谢你。
亚历山大。
发布于 2015-02-08 09:07:45
您发布的是两个(嵌套的)三元运算符:
this.current = idx != undefined ? idx : c;..。其中c是以下结果的结果:
(this.options.start >= 0 && this.options.start < this.items.length ? this.options.start : 0);换句话说,嵌套三值运算符被计算为第一三值运算符的false路径。
如果还不清楚的话,就这样想一想;
if (idx != undefined) {
this.current = idx;
} else if (this.options.start >= 0 && this.options.start < this.items.length) {
this.current = this.options.start;
} else {
this.current = 0;
}发布于 2015-02-08 09:07:57
三元操作符a = cond ? b : c可以解释为:
if (cond) {
a = b;
} else {
a = c;
}如您所见,在"c“部分中有一个嵌套的三元操作符,因此您可以在其中放置另一个嵌套的if,以帮助您将其翻译成英语。希望这能说明问题。
发布于 2015-02-08 09:11:20
您可以使用以下其他方法编写这一行:
if(idx != undefined) {this.current = idx
} else if (this.options.start >= 0 && this.options.start < this.items.length) {this.current = this.options.start
} else {this.current = 0}https://stackoverflow.com/questions/28392282
复制相似问题