javascript - Array.push() 和 Spread 语法之间的区别

标签 javascript arrays algorithm ecmascript-6 dynamic-programming

算法问题陈述:找到与目标总和相加的最小数组。
代码问题:
在以下情况下,我不明白结果的差异:

  • 使用 arr.push() 方法

  • 对比
  • 使用传播语法

  • 请引用下面的评论行。
    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 fasterarray = [...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/

    相关文章:

    javascript - 如何在Apps脚本中获取特定数组元素的索引

    java - 作为注释值的数组常量(字段)

    php - 检查 PHP 数组元素中是否设置了值

    JavaScript - 查找下一次更改的日期(标准或夏令时)

    javascript - JS 正则表达式 : Validate File Names

    javascript - 如何更改 Bootstrap 3 导航栏中事件选项卡的背景颜色?

    algorithm - 插值搜索超出范围

    php - 我需要一个提示才能开始这个编程难题

    javascript - 当服务发出更改时,组件模板变量不会更新( Angular )

    arrays - 我应该如何初始化这个多维数组?