简体   繁体   English

如何将变量多次推入数组而不更改?

[英]How do you push a variable into an array multiple times without it changing?

I'm trying to push some values in an array for something called "Brain.js".我正在尝试将一些值推送到名为“Brain.js”的数组中。 When storing a variable in the array and later changing it, all the variables that were stored in the array change.将变量存储在数组中并稍后更改它时,存储在数组中的所有变量都会更改。 Can someone help me make it so they don't change?有人可以帮我做,这样他们就不会改变吗? I'm having much trouble with this.我在这方面遇到了很多麻烦。

Here's an example:下面是一个例子:

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

Problem is you are updating an existing array a which is already referenced inside first object you pushed.问题是您正在更新已在您推送的第一个对象中引用的现有数组a You should create a copy of an existing array if you do not wish to modify it .如果您不想修改它,您应该创建一个现有数组的副本

 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);

Problem is, that you are not pushing actual number into the array, but reference.问题是,您不是将实际数字推入数组,而是引用。 In other words, you passed twice the reference to same object.换句话说,您传递了两次对同一对象的引用。

What could you do, is create a copy of the object when you are passing it to hold.您可以做的是在传递对象时创建对象的副本。 You can use eg.你可以使用例如。 spread operator.传播运算符。

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

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

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

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