为什么分号会影响我的JavaScript快速排序代码的运行效果?
我正在用JavaScript编写快速排序函数,要按Num属性对如下结构的对象数组进行排序:
let Pairs = [ { ID: 'C', Num: 21 }, { ID: 'B', Num: 45 }, { ID: 'F', Num: 0 }, { ID: 'E', Num: 1 }, { ID: 'D', Num: 9 }, { ID: 'A', Num: 100 } ];
但我发现给partition()函数添加分号后解决了程序的bug:如果swapPair()函数调用后不写分号,程序输出的数组和输入完全一致。我的代码如下:
const swapPair = (a, b) => { let t = a; a = b; b = t; return [a, b] } function partition(a, left, right, pivotIndex) { pivotValue = a[pivotIndex].Num; // 将基准元素移到数组末尾 [a[pivotIndex].ID, a[right].ID] = swapPair(a[pivotIndex].ID, a[right].ID);// 这个分号是关键 [a[pivotIndex].Num, a[right].Num] = swapPair(a[pivotIndex].Num, a[right].Num);// 这个分号是关键 storeIndex = left; for (let i = left; i <= right - 1; i++) { if (a[i].Num <= pivotValue) { [a[storeIndex].ID, a[i].ID] = swapPair(a[storeIndex].ID, a[i].ID);// 这个分号是关键 [a[storeIndex].Num, a[i].Num] = swapPair(a[storeIndex].Num, a[i].Num);// 这个分号是关键 storeIndex = storeIndex + 1 } } // 将基准元素移到正确的排序位置 [a[storeIndex].ID, a[right].ID] = swapPair(a[storeIndex].ID, a[right].ID);// 这个分号是关键 [a[storeIndex].Num, a[right].Num] = swapPair(a[storeIndex].Num, a[right].Num);// 这个分号是关键 return storeIndex }
我猜测问题出在我使用解构赋值的方式上,但我没找到具体原因,希望有人能帮忙解答。
更新
问题确实出在解构赋值上,我的函数返回的是数组,所以这个问题很难被发现:
function foo(){ ... return [a,b,c] } [A,B,C]=foo() [D,E,F]=foo()
如果不写分号,代码会被解析为:
[A,B,C]=[x,y,z] [D,E,F]=[m,n,p] => [A,B,C]=[x,y,z][D,E,F]=[m,n,p] => [A,B,C]=[x,y,z][F]=[m,n,p] => [A,B,C]=[m,n,p]
感谢Felix Kling的解答。
内容的提问来源于stack exchange,提问作者aLonelySheep
相关产品推荐
相关产品推荐

