简体   繁体   English

为什么这段代码返回一个空数组?

[英]Why does this code return an empty array?

Question: Given a collection of distinct integers, return all possible permutations.问题:给定一组不同的整数,返回所有可能的排列。

Example: Input: [1,2,3]示例:输入:[1,2,3]

Desired output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]所需输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1 ]]

Aren't arrays passed by reference in JavaScript? JavaScript 中的数组不是按引用传递的吗? Why is the result array empty when I return it?为什么返回时结果数组为空?

 /** * @param {number[]} nums * @return {number[][]} */ var permute = function(nums) { var result = []; helper(nums, result, []); return result; }; var helper = function(nums, result, cur) { if (cur.length == nums.length) { result.push(cur); } else { for (let i = 0; i < nums.length; i++) { cur.push(nums[i]); helper(nums, result, cur); cur.pop(); } } } console.log(permute([1, 2, 3]));

You only ever create a single cur array when you call helper :当您调用helper时,您只会创建一个cur数组:

helper(nums, result, []);

Which you proceed to mutate and recursively pass around in helper .您继续变异并在helper递归传递。 There's only one array in memory;内存中只有一个数组; by the end, you've .pop ped the last item from the array, and every item in the result array refers to the same object, the now empty cur array.截至去年底,你.pop PED该数组中的最后一个项目,而在每一个项目result数组是指同一个对象,现在空cur阵列。

Instead, clone cur inside the loop, so that when/if it gets pushed, you're pushing a new array, rather than a reference to the old one which will get reused everywhere:相反,在循环cur ,这样当/如果它被推送,你正在推送一个数组,而不是对旧数组的引用,旧数组将在任何地方重用:

for (let i = 0; i < nums.length; i++) {
  const temp = cur;
  cur = [...cur, nums[i]]; // Similar to `.push`, except it creates a new array
  helper(nums, result, cur);
  cur = temp; // Similar to `.pop` - reverts the array to what it was originally
}

 var permute = function(nums) { var result = []; helper(nums, result, []); return result; }; var helper = function(nums, result, cur) { if (cur.length == nums.length) { result.push(cur); } else { for (let i = 0; i < nums.length; i++) { const temp = cur; cur = [...cur, nums[i]]; // Similar to `.push`, except it creates a new array helper(nums, result, cur); cur = temp; // Similar to `.pop` - reverts the array to what it was originally } } } console.log(permute([1, 2, 3]));

No, everything in JavaScript is passed by value.不,JavaScript 中的一切都是按值传递的。 In your function helper , a local variable result will be created and then assigned the value of the argument upon helper call.在您的函数helper ,将创建一个局部变量result ,然后在helper调用时分配参数的值。 What you most likely want to do is: result = helper(nums, result, []);你最有可能想要做的是: result = helper(nums, result, []); . .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM