2016-12-05 73 views
1

我已經寫了一個函數來排列最後一個字符 ,但是我發現函數運行到mushrooms5Sauce6時出現錯誤。任何人都可以幫我解決錯誤,因爲我找不到它?用JavaScript對數組進行排序時出現錯誤

謝謝。

var Dish_name = [ 
    "Layered_Dip2", 
    "Pumpkin_Deviled_Eggs1", 
    "Chinese_fried_egg_noodles_with_shredded_pork_mushrooms5", 
    "Stir_fried_Clams_with_Garlic_and_Black_Bean_Sauce6", 
    "Rosewater_Panna_Cotta4", 
    "Marshmallow_Rabbit3", 
] 

var Dish_show_name = [ 
    "<b>Layered Dip</b>", 
    "<b>Pumpkin Deviled Eggs</b>", 
    "<b>Chinese Fried Egg Noodles with Shredded Pork Mushrooms</b>", 
    "<b>Stir fried Clams with Garlic and Black Bean Sauce</b>", 
    "<b>Rosewater Panna Cotta</b>", 
    "<b>Marshmallow Rabbit</b>", 
] 

var Dish_url = [ 
    "http://3.1m.yt/BqHJBVM.jpg", 
    "http://4.1m.yt/2yq6CpE.png", 
    "http://3.1m.yt/k-owd2.jpg", 
    "http://4.1m.yt/zvcLufM.png", 
    "http://3.1m.yt/Fw9Wdcw.png", 
    "http://1.1m.yt/INLaIN-.jpg" 
]  

$("#cook").click(function() { 
    var i, j, temp, temp2, temp3; 
    for (i = 0; i < 6; i++) { 
     for (j = 1; j < 6; i++) { 
      if (Dish_name[i].slice(-1) > Dish_name[j].slice(-1)) { 
       temp = Dish_name[i]; 
       temp2 = Dish_show_name[i]; 
       temp3 = Dish_url[i]; 
       Dish_name[i] = Dish_name[j]; 
       Dish_show_name[i] = Dish_show_name[j]; 
       Dish_url[i] = Dish_url[j]; 
       Dish_name[j] = temp; 
       Dish_show_name[j] = temp2; 
       Dish_url[j] = temp3; 
       alert(Dish_name[i]); 
       alert(Dish_name[j]); 
       alert(Dish_name[i].slice(-1)); 
       alert(Dish_name[j].slice(-1)); 
      } 
     } 
    } 
}) 
+2

什麼是錯誤?問題是什麼? – Dekel

+0

@Dekel在'S'之後'm'因爲它是小寫而被排序。 – andlrc

+0

@Dekel我認爲這是第三個將與第二個匹配後,然後排序1,2,5,6,4,3 .... 但我不知道如何解決它... – kennytsz

回答

1

問題是你的氣泡排序;內循環應該是:

for (i = 0; i < 6; i++) { 
    for (j = i + 1; j < 6; j++) { 
      ^^^^^  ^

內環應該從下一個元件的電流i後運行,而不是在開始每1本輪調控。而我剛剛注意到,內循環也增加了i,而不是j

+0

你打我它! =) –

0

下面是JavaScript中氣泡排序的一個很好的實現,它有點緊湊並且修復了循環中的變量錯誤。

function bubble(arr) { 
     var len = arr.length; 

     for (var i = 0; i < len ; i++) { 
     for(var j = 0 ; j < len - i - 1; j++){ // there was an error in your code here 
     if (arr[j] > arr[j + 1]) { 
      // swap 
      var temp = arr[j]; 
      arr[j] = arr[j+1]; 
      arr[j + 1] = temp; 
     } 
     } 
     } 
     return arr; 
    } 

document.write(bubble([1,9,2,3,7,6,4,5,5])); 
相關問題