【问题标题】:How do you push a variable into an array multiple times without it changing?如何在不改变变量的情况下多次将变量推送到数组中?
【发布时间】:2020-10-14 15:46:49
【问题描述】:

我正在尝试将一些值推送到一个名为“Brain.js”的数组中。当将变量存储在数组中并稍后更改它时,存储在数组中的所有变量都会更改。有人可以帮我做到,这样他们就不会改变吗?我在这方面遇到了很多麻烦。

这是一个例子:

var hold = ([

]);
var a = [1, 1, 1]
var b = [2];

hold.push(
    { input: a, output: b }
);

console.log(hold); // returns [ { input: [ 1, 1, 1 ], output: [ 2 ] } ]

a[2] = 2;
b = [3];

hold.push(
  { input: a, output: b }
);

console.log(hold);
// Expected output: [ { input: [ 1, 1, 1 ], output: [ 2 ] }, { input: [ 1, 1, 2 ], output: [ 3 ] } ]
// What it really returns: [ { input: [ 1, 1, 2 ], output: [ 2 ] }, { input: [ 1, 1, 2 ], output: [ 3 ] } ]

【问题讨论】:

    标签: javascript arrays brain.js


    【解决方案1】:

    问题是,您不是将实际数字推入数组,而是引用。换句话说,你传递了两次对同一个对象的引用。

    你可以做的是,当你将它传递给持有时创建一个对象的副本。您可以使用例如。传播运算符。

    hold.push(
        { 
            input: ...a, 
            output: ...b
        }
    );
    

    您可以在此处了解更多信息 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

    【讨论】:

      【解决方案2】:

      问题是您正在更新现有数组a,该数组已在您推送的第一个对象中引用。如果您不想修改现有数组,则应创建一个副本

      var hold = ([
      
      ]);
      var a = [1, 1, 1]
      var b = [2];
      
      hold.push({
        input: a,
        output: b
      });
      
      console.log(hold);
      
      a = [...a]; // create a new copy of a
      a[2] = 2;
      b = [3];
      
      hold.push({
        input: a,
        output: b
      });
      
      console.log(hold);

      【讨论】:

        猜你喜欢
        • 2021-11-29
        • 1970-01-01
        • 1970-01-01
        • 2016-11-17
        • 2020-11-29
        • 2021-07-01
        • 2022-11-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多