This question already has answers here:
Question mark and colon in JavaScript
                                
                                    (7个答案)
                                
                        
                        
                            What does the question mark and the colon (?: ternary operator) mean in objective-c?
                                
                                    (13个回答)
                                
                        
                                5年前关闭。
            
                    
我正在寻找一种解决方案,以获取最大的素数,并找到了可以运行的脚本,但是?循环中有一个for(问号)。我想知道?是做什么的?

<script type="text/javascript">
    n=317584931803;
    for(i=2;n>1;n%i?i++:(n/=i,document.write(i+' ')));
</script>


而且,如果您也可以解释此脚本的确切功能,我将不胜感激。

最佳答案

它称为conditional operator。基本上,x ? y : z表示如果x为true,则求值并返回y,否则求值并返回z。这样,它就像一个内联if/else语句。

在这种情况下,我们可以像这样分解您的代码:

n=317584931803;
for(i=2;n>1;n%i?i++:(n/=i,document.write(i+' ')));


等效于:

var n=317584931803;
for (var i=2; n>1; n % i ? i++ : (n /= i, document.write(i + ' '))) {
    // do nothing
}


但是,此for循环可以更清晰地写为while循环:

var n=317584931803, i = 2;
while (n > 1) {
    n % i ? i++ : (n /= i, document.write(i + ' ');
}


条件运算符可以扩展为:

var n=317584931803, i = 2;
while (n > 1) {
    if (n % i > 0) {
        i++;
    } else {
        n = n / i;
        document.write( i + ' ');
    }
}

09-10 10:19
查看更多