且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么我的置换算法为所有置换都提供相同的结果?

更新时间:2023-11-24 08:57:16

这是简单的(堆)引用与(堆栈)值问题.原因很简单:所有递归调用中的arr都引用内存中的同一数组.因此,当您调用newArr.push(arr)时,对同一对象的另一个引用将添加到结果列表中.当您执行swap时,您将newArr的所有元素都交换为指向相同数组的元素.另请参见在JavaScript中按值复制数组,以获取可能的解决方法. (基本上使用 Array.slice 创建独立副本的方法).

This is simple (heap) reference vs. (stack) value question. The reason is quite simple: arr in all recursive calls references the same array in memory. Thus when you call newArr.push(arr) another reference to the same object is added to the result list. And when you do swap, you swap elements for all elements of newArr as they point to the same array. See also Copying array by value in JavaScript for a possible workaround. (Basically use Array.slice method to create an independent copy).