使用array.length时出现未定义的错误

时间:2014-03-31 14:07:46

标签: javascript

我正在使用JavaScript实现冒泡排序方法,这是我目前的代码:

 // 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]

当我运行这个时,我一直得到'无法读取未定义的属性。

但是,我可以在for循环之前调用console.log(array.length)并返回一个值。

以下是我的代码repl.it

为什么我得到'未定义'?

2 个答案:

答案 0 :(得分:2)

根据我的评论:您需要再次将array传递给排序功能:

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

答案 1 :(得分:0)

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

这里没有参数返回sort()。