我正在用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]


当我运行此命令时,我不断收到“无法读取未定义的属性.length的信息”

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

这是我的代码的repl.it

为什么我会得到“未定义”?

最佳答案

根据我的评论:您需要再次将array传递给sort函数:

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

关于javascript - 使用array.length时发生未定义的错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22763789/

10-11 10:32
查看更多