I was creating a code where I need to use some variables from a global scope, when I made my local = global, I've noticed the changes I've made in the local scope were being modified into the global scope.
This is an example of what I am talking about
global = [];
load_global();
use_global();
function load_global() {
for (i = 0; i < 10; i++) {
global.push(i);
}
}
function use_global() {
local = [];
local = global;
for (i = 0; i < 5; i++) {
global.push("x");
}
console.log(local);
}
JSbin Example
Is there a way to use the values of a global array, but without changing it?
Besides old school Array#slice, you can use the ES6 method Array.from, which is designed for such scenarios:
var local = Array.from(global)
This method can be used on array-like objects or any iterable values, which don't have a slice method. You may say Array.prototype.slice.call(). Oops you are right, but isn't that annoying?
Besides, you can pass a mapping function to it as well. For example:
Array.from('asdf', c => c.toUpperCase()) // ["A", "S", "D", "F"]
Comparing to ES5 style, you can see how neat ES6 is:
Array.prototype.slice.call('asdf').map(function(c){return c.toUpperCase()})
Read MDN doc for more.
On the other hand, the method is not widely supported at the moment, you need babel or a polyfill. But ES6 is the future, eventually it'll be fully supported by all major browsers.
You can try copying the global array
local = global.slice()
btw you might wanna use var keyword to make that array local. Without it the "local" array will be accessible from outside of the function
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With