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://*.com/posts/21558099/editghout the whole page?
它不起作用,我认为这可能是因为颜色只是一个本地数组。有什么方法可以让它工作://*.com/posts/21558099/editghout整个页面?
4 个解决方案
#1
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;
#2
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()});
#3
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();
#4
-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.
可能你需要在几个程序中使用该变量。把它放在外部文件中,php通过include添加它。将其视为全局变量。
#1
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;
#2
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()});
#3
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();
#4
-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.
可能你需要在几个程序中使用该变量。把它放在外部文件中,php通过include添加它。将其视为全局变量。