首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >复三值算子与逻辑算子

复三值算子与逻辑算子
EN

Stack Overflow用户
提问于 2015-02-08 09:03:07
回答 5查看 224关注 0票数 0

嘿,伙计们,我正在调试一个非常小的java脚本插件,我似乎已经弄清楚了其中的大部分,但是我在理解以下功能时遇到了一些困难:

代码语言:javascript
复制
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的优秀文档也有所帮助,但是,我仍然很难理解下面的内容:

代码语言:javascript
复制
this.current = idx != undefined ? idx : this.options.start >= 0 && this.options.start < this.items.length ? this.options.start : 0;

三元运算符和逻辑运算符的结合似乎真的令人困惑,为了简化上面的操作,我试着用通俗易懂的英语阅读它,我最好的解释是:

如果idx是,不等于与未定义,而等于,则是this.current。我被困在这上面了,接下来会发生什么我都猜不出来。如果有人能用英文来解释这句话,那就太好了!

编辑:::我刚刚在评论中看到了一个很好的文章链接,所以我只想澄清一下,考虑到下面的代码行(一个嵌套的三元操作符):

代码语言:javascript
复制
int i = 5;
string result = i % 2 == 0 ? "a" : i % 3 == 0 ? "b" : i % 5 == 0 ? "c" : i % 7 == 0 ? "d" : "e"; 

最后,e的功能更像是开关情况下的默认情况,对吗?谢谢你。

亚历山大。

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2015-02-08 09:07:45

您发布的是两个(嵌套的)三元运算符:

代码语言:javascript
复制
this.current = idx != undefined ? idx : c;

..。其中c是以下结果的结果:

代码语言:javascript
复制
 (this.options.start >= 0 && this.options.start < this.items.length ? this.options.start : 0);

换句话说,嵌套三值运算符被计算为第一三值运算符的false路径。

如果还不清楚的话,就这样想一想;

代码语言:javascript
复制
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;
}
票数 1
EN

Stack Overflow用户

发布于 2015-02-08 09:07:57

三元操作符a = cond ? b : c可以解释为:

代码语言:javascript
复制
if (cond) {
    a = b;
} else {
    a = c;
}

如您所见,在"c“部分中有一个嵌套的三元操作符,因此您可以在其中放置另一个嵌套的if,以帮助您将其翻译成英语。希望这能说明问题。

票数 1
EN

Stack Overflow用户

发布于 2015-02-08 09:11:20

您可以使用以下其他方法编写这一行:

代码语言:javascript
复制
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}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28392282

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档