search

Home  >  Q&A  >  body text

What is the difference between the code arr[pivotIndex] and arr.splice(pivotIndex,1)[0]?

Using arr[pivotIndex] instead of arr.splice(pivotIndex,1)[0] reports an error. The error message is as follows:

The code is as follows, the commented out code is the error code:

function quickSort (arr) {
        if (arr.length<=1) {
            return arr;
        };
        let left = [],
            right = [],
            pivotIndex = Math.floor(arr.length/2);
        //let pivot = arr[pivotIndex],   //直接获取arr[pivotIndex]赋值给pivot时报错
        let pivot = arr.splice(pivotIndex,1)[0]; //用词句代码可以正确输出排序结果
        for (let i=0; i<arr.length; i++) {
            if (arr[i] <= pivot) {
                left.push(arr[i]);
            } else {
                right.push(arr[i]);
            }
        }
        return quickSort(left).concat(pivot,quickSort(right));
    }

    console.log('纯JS快排结果: '+quickSort(newarr))
黄舟黄舟2741 days ago1143

reply all(1)I'll reply

  • 大家讲道理

    大家讲道理2017-06-26 10:52:53

    "Please" read the documentation: https://developer.mozilla.org...

    reply
    0
  • Cancelreply