0

I have an array that is made inside of a function like this:

function easy() {
    var colors = ["white", "red", "orange", "yellow", "green", "blue", "purple", "gray", "white", "red", "orange", "yellow", "green", "blue", "purple", "gray"];
}

I call this function through an onclick on a radio button, but when I do this later:

colors.sort(function() {return 0.5 - Math.random()});

it doesn't work, I think it might be because colors is just a local array. Is there any way to make it work throuhttp://stackoverflow.com/posts/21558099/editghout the whole page?

CPC
  • 163
  • 5
  • 17

4 Answers4

2

If you declare your array outside of the function its scope is global :

var colors;
function easy() {
    colors = ["white", "red", "orange", "yellow", "green", "blue", "purple", "gray", "white", "red", "orange", "yellow", "green", "blue", "purple", "gray"];
}
easy(); // Here colors is defined;
luxcem
  • 1,807
  • 22
  • 37
0
var colors;
function easy() {
   colors = ["white", "red", "orange", "yellow", "green", "blue", "purple", "gray", "white", "red", "orange", "yellow", "green", "blue", "purple", "gray"];
};
easy();
colors.sort(function() {return 0.5 - Math.random()});
Danilo Valente
  • 11,270
  • 8
  • 53
  • 67
0

Are you looking to encapsulate it?

var easy = {
   colors: ["white", "red", "orange", "yellow", "green", "blue", "purple", "gray", "white", "red", "orange", "yellow", "green", "blue", "purple", "gray"],
   hello: function() { alert("Hello") }
}

alert( easy.colors.sort(function() {return 0.5 - Math.random()}) );
easy.hello();
Alex K.
  • 171,639
  • 30
  • 264
  • 288
-1

Probably you will need to use that variable in several programs. Put it in an external file, php an add it via include. Consider it like global variables.

gtryonp
  • 397
  • 5
  • 13
  • This is extremely needlessly complicated for something that's simply accomplished by moving the variable to global scope. – Brian S Feb 04 '14 at 17:00
  • In my scneario: "Probably you will need to use that variable in several programs". I have 20+ sites running in different host servers. For me, add/replace a new global variable means change only one program and replace only one program to all. For me, is extremely useful. – gtryonp Feb 05 '14 at 14:25