如何将函数的结果设置为全局变量

时间:2010-03-25 15:09:26

标签: javascript global-variables

我确信这很简单,而且我正在绘制一个巨大的空白,但是如何将函数的结果设置为全局变量?

示例,我想将数组“colors”中的第一个“颜色”设置为全局变量“color”(我知道这个例子没有多大实际意义,但它只是为了说明我的问题):

var color = "";

function selectColor () {
    var colors = ["blue","red","green","yellow"];
    var color = colors[0];
    return color;
}

window.onload = function () {
    selectColor ();
    alert(color);
}

3 个答案:

答案 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关键字在selectColor()中创建一个局部变量;你不希望这样。
  • 不需要退货声明;你没有抓住它。

在任何情况下,在这个确切的例子中,这样做会更干净:

var color = "";

function selectColor () {
    var colors = ["blue","red","green","yellow"];
    return colors[0];
}

window.onload = function () {
    color = selectColor ();
    alert(color);
}