简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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