Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript (JS) function array equality works as pointer? How to just use the variables?

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?

like image 812
VanHalenBR Avatar asked Jul 24 '26 18:07

VanHalenBR


2 Answers

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.

like image 77
Leo Avatar answered Jul 27 '26 19:07

Leo


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

like image 22
memo Avatar answered Jul 27 '26 18:07

memo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!