我确信这很简单,而且我正在绘制一个巨大的空白,但是如何将函数的结果设置为全局变量?
示例,我想将数组“colors”中的第一个“颜色”设置为全局变量“color”(我知道这个例子没有多大实际意义,但它只是为了说明我的问题):
var color = "";
function selectColor () {
var colors = ["blue","red","green","yellow"];
var color = colors[0];
return color;
}
window.onload = function () {
selectColor ();
alert(color);
}
答案 0 :(得分:5)
如果您从var
函数中color
删除selectColor()
声明,它应该适用于您:
var color = "";
function selectColor () {
var colors = ["blue","red","green","yellow"];
color = colors[0];
return color;
}
window.onload = function () {
selectColor ();
alert(color);
}
答案 1 :(得分:2)
var color = "";
function selectColor() {
var colors = ["blue","red","green","yellow"];
var color = colors[0];
return color;
}
window.onload = function() {
color = selectColor();
alert(color);
}
答案 2 :(得分:0)
回答你的问题:
var color = "";
function selectColor () {
var colors = ["blue","red","green","yellow"];
color = colors[0];
}
window.onload = function () {
selectColor ();
alert(color);
}
在任何情况下,在这个确切的例子中,这样做会更干净:
var color = "";
function selectColor () {
var colors = ["blue","red","green","yellow"];
return colors[0];
}
window.onload = function () {
color = selectColor ();
alert(color);
}