javascript - 带有逻辑运算符的复杂三元运算符

标签 javascript

嘿,大家好,我正在调试一个非常小的 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/

相关文章:

javascript - 如何使用 Closure Compiler 优化 Javascript 并保留函数名称?

javascript - HTML/CSS/JS切换不同谷歌日历是同一个框架

javascript - 跳上云端 HackerRank

javascript - 使用多个选项 JQuery 添加更多问题

javascript - 初始化开关切换元素

javascript - 如何使用 SSL 从 extjs 调用 rest

javascript - 如果父级具有 onclick 绑定(bind),则复选框单击将被忽略

javascript - 根据点击次数增加值(value)

javascript - 鼠标移开时停止功能 | JS

javascript - 如何在聚合中从数组中删除数据而不干扰 mongodb 中的外部数据