Access to arrays of other HTML functions

0

I have this code:

    function shuffle(array) {
    var counter = array.length, temp, index;

    // While there are elements in the array
    while (counter > 0) {
    // Pick a random index
        index = Math.floor(Math.random() * counter);

    // Decrease counter by 1
        counter--;

     // And swap the last element with it
        temp = array[counter];
        array[counter] = array[index];
        array[index] = temp;
    }

    return array;
    }   

And then I have this:

function somethingOne(){
  shuffle(array);
  ... 
}

My goal is to create a somethingTwo() function that uses the array that was shuffled in the somethingOne() function, how can I do this?

    
asked by anonymous 22.07.2015 / 15:41

3 answers

1
function somethingOne(){
  shuffle(array);
  ... 
}

In order to access the Array outside of a function, you will have to create it outside the

Var array; // Fora de qualquer Funcao!

// Then the functions here could use the same Array created above.

    function somethingOne(){
      array = shuffle(array);
      ... 
   }

So the Array would be messed up in every program.

    
22.07.2015 / 15:58
0

If the variable passed to the function is global, you can access it anywhere, even after the function is called.

If it is not global, you can do something like var algo = funcao(argumento); and use the variable that received the function return.

    
22.07.2015 / 16:00
0

It is not good practice to use global variables for n reasons. Perhaps the best way for this case would be to work with a literal object. See:

var obj = {
  arr: [],
  suffle: function ( someArray ) 
  {
    someArray.push('foo');
  },
  somethingOne: function () 
  {
     // use o operador this para acessar os metodos e atributos
     this.suffle( this.arr );
  },
  somethingTwo: function() {
    this.somethingOne();
    console.log(this.arr);
  }
};
obj.somethingTwo(); // ['foo']
    
22.07.2015 / 17:42