简体   繁体   中英

How can I make an array act as a buffer?

I've got an array called routeStart that a user can push coordinates into. Because I want the user to make changes on the map on my site to the current route and also make a new route at the same time I have another array called preRouteStart. The coordinates are first pushed into preRouteStart so that the original routeStart can still be used to make changes to the route currently on the map.

preRouteStart.push(coords);

Then when the user presses a button and a completely new route is made preRouteStart gets turned into routestart like this.

onClick('button', function(evt) {
routeStart = preRouteStart;
});

function onClick(id, callback) {
  document.getElementById(id).addEventListener('click', callback);
};

this seems to work well at first, with console.log I checked that when adding coordinates they only get pushed into preRouteStart, and then into routeStart when the button is pressed. But after the button has been pressed and new coordinates are added the coordinates will immediately get pushed into the non-pre routeStart. Why does this happen?

My first instinct is this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

Have you tried using a spread operator here: routeStart = [...preRouteStart]; instead of routeStart = preRouteStart;

From the docs:

Spread syntax can be used when all elements from an object or array need to be included in a list of some kind.

In the above example, the defined function takes x, y, and z as arguments and returns the sum of these values. An array value is also defined.

When we invoke the function, we pass it all the values in the array using the spread syntax and the array name —...numbers.

If the array contained more than three numbers, eg [1, 2, 3, 4], then it would still work fine, except that all four would be passed, but only the first three would be used unless you added more arguments to the function, eg:

function sum(x, y, z, n) {
  return x + y + z + n;
}

The above example is somewhat rigid; the real value in spread syntax is that it works with the same value, no matter how many elements are contained in the object, array, etc.

It is commonly used when you want to add a new item to a local data store, or display all stored items plus a new addition. A very simple version of this kind of action could look like so:

let numberStore = [0, 1, 2];
let newNumber = 12;
numberStore = [...numberStore, newNumber];

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