算法问题陈述:找到与目标总和相加的最小数组。
代码问题:
在以下情况下,我不明白结果的差异:
对比
请引用下面的评论行。
Spread 语法返回正确的解决方案,而 .push() 方法继续插入同一个数组。我不明白为什么它一直在内存中引用同一个数组。
提前谢谢了!
let howSum = (target, arr, memo = {}) => {
if (target in memo) return memo[target];
if (target === 0) return [];
if (target < 0) return null;
let smallest = null;
for (let e of arr) {
if (howSum(target - e, arr, memo) !== null) {
let result = howSum(target - e, arr, memo);
// result.push(e);
result = [...result, e];
if (smallest === null || result.length < smallest.length) {
smallest = result;
}
}
}
memo[target] = smallest;
return smallest;
};
console.log(howSum(10, [1, 2, 5])); // [5, 5]
最佳答案
array.push(element)
与 array = [...array, element]
Array.push
在现有数组的末尾添加一个元素,而扩展语法创建一个全新的数组。例如,以下代码将抛出错误,因为我们试图重新定义 const
:
const array = ["foo", "bar"];
array = [...array, "baz"]; // Uncaught TypeError: invalid assignment to const 'array'
Array.push
添加到现有数组,因此无需重新定义:const array = ["foo", "bar"];
array.push("baz"); // No error; "baz" is successfully added to the end of the array.
另一个区别是速度。 array.push(element)
是 ~2,500 times faster比 array = [...array, element];
如pointed out by @FelixKling , 扩展语法本身 不是 创建一个新数组。你也可以在这样的函数中使用扩展语法:
myFunction(...myArray)
.这将使用数组元素作为参数。换句话说,...myArray
不会创建新数组,而是 [...myArray]
将要。只是一个值得注意的小细节。为什么你的循环一直引用内存中的同一个数组
The Spread syntax returns the correct solution, while the .push() method keeps on pushing onto the same array. I don't understand why it keeps referencing the same array in memory.
JavaScript 中的对象(JavaScript 数组是对象)是引用类型,而不是值类型。因此,使用扩展语法,您创建了一个新数组 (
result
),但仍将旧数组 ( arr
) 提供给您的函数。当您使用 Array.push
,您修改提供给您的函数的数组。并且由于您修改了提供的数组(而不是创建本地数组),您将继续使用数组中的新值调用您的函数。当你使用扩展语法时,你创建了一个新数组(所以 result
不引用 arr
数组),当你用 arr
调用你的函数时参数,您仍然具有与第一次调用该函数时相同的值。@trincot 写道 a neat break down你的代码中发生了什么。
这是您可以在 JavaScript 控制台中进行的实验:
const myArray = ["foo", "bar"];
function changeArray(arrayParameter) {
const arrayVariable = arrayParameter;
// We are still referencing the array that was supplied to our function, so
// although it looks like we tried to duplicate the array, arrayVariable.push,
// arrayParameter.push, and myArray.push will all modify the same array.
arrayVariable.push("baz");
}
changeArray();
console.log(myArray); // ["foo", "bar", "baz"]
关于javascript - Array.push() 和 Spread 语法之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65349847/