2014-03-31 51 views
0

我正在用JavaScript實現冒泡排序的方法,這是我目前的代碼:未定義的錯誤,而使用array.length

// Sort array (ascending) 
function sort(array) { 

    var sortedArray = array; 
    // This swapped 'flag' tells the function whether or not it will 
    // need to iterate over the array again to continue sorting 
    var swapped = false; 

    for(var i = 1; i < array.length; i++) { 
    var prev = array[i - 1]; 
    var current = array[i]; 

    // If the previous number is > than the current, swap them around 
    if(prev > current) { 
     swapped = true; 

     sortedArray[i] = prev; 
     sortedArray[i - 1] = current; 
    } 

    } 
    // If there has been a swap, sort over the array again 
    if(swapped) { 
    return sort(); 
    } 

    return sortedArray; 
} 


var testArray = [1, 4, 27, 3, 2]; 


// Run the sort function 
sort(testArray); // [1, 2, 3, 4, 27] 

當我運行它,我不斷收到「無法讀取的性能。長度undefined'

但是,我可以在for循環之前調用console.log(array.length)並返回一個值。

這是我的代碼repl.it

爲什麼我得到'undefined'?

+6

'返回排序(陣列)''不返回排序()'? – Andy

+0

謝謝安迪,就是這樣!我想在嘗試其他事情之前我需要週一早上的咖啡。再次感謝! – HelloWorld

回答

2

按我的意見:你需要在array再次傳遞給排序函數:

if (swapped) { 
    return sort(array); 
} 
+1

把這個標記爲答案,給這個傢伙一些信用^ _ ^ – weeknie

0
// If there has been a swap, sort over the array again 
    if(swapped) { 
    return sort(); 
    } 

你在這裏沒有參數返回sort()。