JavaScript 中的双三元
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14427696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Double ternary in JavaScript
提问by Sethen
I was going through some stuff in the jQuery source, specifically the inArray
method and I found this line of code:
我正在浏览 jQuery 源代码中的一些东西,特别是inArray
方法,我发现了这行代码:
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
What I am seeing is two ternary operators, but I have no idea how this is used. I understand how the ternary operator works, but I have never seen it used like this before. How does this piece of code work??
我看到的是两个三元运算符,但我不知道如何使用它。我了解三元运算符的工作原理,但我以前从未见过它像这样使用。这段代码是如何工作的??
回答by Niet the Dark Absol
Just break it down like you would 1 + 2 + 3
:
就像你一样把它分解1 + 2 + 3
:
if (i) {
if (i < 0) {
i = Math.max(0, len + i);
} else {
i = i; // no-op
}
} else {
i = 0; // also no-op, since if `i` were anything else it would be truthy.
}
In fact, that whole line seems inefficient to me. Personally I'd just use:
事实上,整条线对我来说似乎效率低下。我个人只会使用:
if (i < 0) {
i = Math.max(0, len + i);
}
回答by Kevin Bowersox
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
Breaks down to:
分解为:
var i;
if(i){
if(i<0){
i = Math.max(0, len + i);
}else{
i = i;
}
}else{
i = 0;
}
回答by Gato
By any chance, is "i" an index into an array and "len" the length of the array?
无论如何,“i”是数组的索引,而“len”是数组的长度吗?
If it is so, then that line would do the following:
如果是这样,那么该行将执行以下操作:
if i can be equated to false, then assume it's 0
else if i is positive or 0, then take it as it is
else if i is negative, then consider it an index counting from the end of the array (ie. if i==-1, it means the last element of the array).
如果 i 可以等同于 false,则假设它为 0
否则如果 i 是正数或 0,则照原样
否则,如果 i 为负,则将其视为从数组末尾开始计数的索引(即,如果 i==-1,则表示数组的最后一个元素)。
回答by Balaji Sivanath
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
reads to
读到
i = i ? ( i < 0 ? Math.max( 0, len + i ) : i ) : 0;