Array.ush()和扩展语法之间的差异 [英] Difference between Array.push() and Spread syntax

查看:32
本文介绍了Array.ush()和扩展语法之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

算法问题说明:查找与目标总和相加的最小数组。

代码问题: 我不理解以下情况下结果的差异:

  • 使用arr.ush()方法

  • 使用扩展语法

请参考下面的注释行。

扩散语法返回正确的解,而.ush()方法继续压入相同的数组。我不明白为什么它总是引用内存中的同一数组。

提前表示感谢!

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)array = [...array, element];


作为pointed out by @FelixKling,扩散语法本身不会创建新数组。您还可以在如下的函数中使用扩展语法:myFunction(...myArray)。这将使用数组元素作为参数。换句话说,...myArray不会创建新数组,但[...myArray]会。这只是一个值得注意的小细节。


为什么您的循环总是引用内存中的同一数组

扩散语法返回正确的解,而.ush()方法继续压入相同的数组。我不明白为什么它总是引用内存中的同一数组。

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"]

这篇关于Array.ush()和扩展语法之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆