嘿,大家好,我正在调试一个非常小的 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 不等于 为 undefined 并且 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
最终的功能更像是 switch case 中的默认 case,对吗? 。
谢谢 。
亚历山大.
最佳答案
您发布的是两个(嵌套)三元运算符:
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;
}
关于javascript - 带有逻辑运算符的复杂三元运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28392282/