Access to arrays of other HTML functions

Asked

Viewed 56 times

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 function somethingTwo() which uses the array that has been shuffled in the function somethingOne(), how can I do this?

  • But what do you want to do in this function? Where the function will be called?

  • I have a deck of cards, where the array is the 52 images... I in somethingOne() deck the cards, and deliver 13 cards to each "player" ... What I wanted was a function for example somethingTwo() sort each player’s "hand", that is, sort each player’s cards... You know what I mean?

  • And for that I need to access the cards that were shuffled in somethingOne function()

3 answers

1

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

To access the Array outside a function the same must have

Var array; // Fora de qualquer Funcao!

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

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

So the Array was confused throughout the program.

0

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

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

0

It is not good practice to use global variables by 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']

Browser other questions tagged

You are not signed in. Login or sign up in order to post.