嵌套if语句vs&&运算符javascript jquery

时间:2013-11-19 14:00:24

标签: javascript jquery if-statement

我一直在使用&&和来自嵌套if语句转换我的一些代码。运算符,其中一个嵌套语句以旧的形式工作,但一旦转换停止运行。

我做错了吗?

考虑:

;(function( $, window ){
    var jsonData = <venda_block></venda_block>,

    isActive = jsonData.isActive, // false = off, true = on
    spendThreshold = jsonData.spendThreshold,
    displayThreshold = jsonData.displayThreshold,
    orderTotal = <venda_total>,
    remainingSpend = spendThreshold - orderTotal;

    $('.deliveryType').text(jsonData.deliveryType);

    if (isActive) {
    if (orderTotal >= displayThreshold) {
    if (!(orderTotal >= spendThreshold)) {
        $('.freeDeliveryBlurb2').show();
        $('.remainingSpend').html(remainingSpend);
    }}}
    }( jQuery, window ));

&安培;&安培;

if (isActive) {
    if (orderTotal >= displayThreshold && !(orderTotal >= spendThreshold)) {
        $('.freeDeliveryBlurb2').show();
        $('.remainingSpend').html(remainingSpend);
    }}
    }( jQuery, window ));

1 个答案:

答案 0 :(得分:1)

如果你想转换以下if块&amp;&amp; :

if (isActive) {
if (orderTotal >= displayThreshold) {
if (!(orderTotal >= spendThreshold)) {
    $('.freeDeliveryBlurb2').show();
    $('.remainingSpend').html(remainingSpend);
}}}

结果可能是这样的:

if (isActive && orderTotal >= displayThreshold && !(orderTotal >= spendThreshold)) {
    $('.freeDeliveryBlurb2').show();
    $('.remainingSpend').html(remainingSpend);
}

或者,as!(orderTotal&gt; = spendThreshold)相当于(orderTotal&lt; spendThreshold),如下所示:

if (isActive && orderTotal >= displayThreshold && orderTotal < spendThreshold) {
    $('.freeDeliveryBlurb2').show();
    $('.remainingSpend').html(remainingSpend);
}

请注意,原始代码中可能存在错误,因为下面的if语句写错:

if (orderTotal >= displayThreshold {

而不是

if (orderTotal >= displayThreshold) {