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))
"Please" read the documentation: https://developer.mozilla.org...