2016-07-29 38 views
-1

Javascript。我想要顯示的業務,如果res.display[i].type爲1,經濟如果res.display[i].type爲2如果條件代碼總是給出相同的值,那麼Javascript會顯示總是一個值

$.ajax({ 
     type: frm.attr('method'), 
     url: frm.attr('action'), 
     data: frm.serialize(), 
     success: function (data) 
      { 
       var res = $.parseJSON(data); 
       if(res.status == true) 
       { 

        var results='';   

        for(var i=0; i<res.display.length; i++) 
        {  
         console.log(res.display[i].type); ` 

這給6 1和三個2,但如果條件始終顯示2.

     if(res.display[i].type='1') 
         { 
          var b="Business"; 
         } 
         if(res.display[i].type='2') 
         { 
          var b="Economy"; 
         } 

         results +='Seat ID:'+ res.display[i].seat_id + 
            '<br>Seat:'+res.display[i].seat+ 
            '<br>Type:'+b+ 

這裏變量b總是2.如果我使用res.display[i].type而不是顯示正確的變量。即六個1和三個2,而不是我想展示商業或經濟的數字。

        '<br><br>'; 
         $('#result').html(results); 
        } 
       } 

回答

1

你平等的經營者是錯誤的,你正在使用=代替==。更換

if(res.display[i].type='1') 

if(res.display[i].type='2') 

if (res.display[i].type == '1') 

if (res.display[i].type == '2') 

你做的方式,res.display[i].type被賦值爲'1',那就是它總是進入這種狀態的原因。

1

對於同一類型的任何類型或===使用比較運算==,不=它指定的值,因爲你已經寫了res.display[i].type='1'第一,res.display[i].type值由1代替,你得到總是1

if(res.display[i].type=='1') 
{ 
    var b="Business"; 
} 
if(res.display[i].type=='2') 
{ 
    var b="Economy"; 
} 
1

'='是您應該使用'=='它檢查比較運算符的日期,

if(res.display[i].type=='1') 
    { 
    var b="Business"; 
    } 
if(res.display[i].type=='2') 
    { 
    var b="Economy"; 
    } 

通過使用=您可以爲某個值賦值。

x = 1 //x now equals 1 
x = 2 //x now equals 2 

使用==你檢查,如果事情是等於別的東西。這不是嚴格

x == 1 //is x equal to 1? (False) 
x == 2 //is x equal to 2? (True) 
true == 1 //does the boolean value of true equal 1? (True) 

使用===你檢查,如果事情是等於別的東西。這也是嚴格的。

x === 1 //is x equal to 1? (False) 
x === 2 //is x equal to 2? (True) 
true === 1 //does the boolean value of true equal 1? (False)