当我尝试使用函数“重用”代码时,它会给出错误的结果

时间:2013-06-28 12:28:57

标签: javascript function google-maps-api-3

我在google地图API中有以下代码:

var TC1image0 = "";
var TC1Intensity0 = "";
if (TC1wind0 < 41) { TC1Intensity0="Low Pressure Area"; TC1image0="lpagoogle.png"; }
else if (TC1wind0 < 63) { TC1Intensity0="Tropical Depression";  TC1image0="tdgoogle.png"; }
else if (TC1wind0 < 88) { TC1Intensity0="Tropical Storm"; TC1image0="tsgoogle.png";}
else if (TC1wind0 < 118) { TC1Intensity0="Severe Tropical Storm"; TC1image0="stsgoogle.png"; }
else if (TC1wind0 < 150) { TC1Intensity0="Typhoon"; TC1image0="tygoogle.png"; }
else if (TC1wind0 < 185) { TC1Intensity0="Severe Typhoon"; TC1image0="stygoogle.png"; }
else { TC1Intensity0="Super Typhoon"; TC1image0="sutygoogle.png"; }

在我尝试使用功能之前,我只是在每次需要时重复这些代码,直到TC1wind6 / TC1Intensity6 / TC1image6 ...... 这完全是浪费空间。所以我尝试使用函数修改代码:

function Intensity(TCwind, TCIntensity, TCimage) {
if (TCwind < 41) { TCIntensity="Low Pressure Area"; TCimage="lpagoogle.png"; }
else if (TCwind < 63) { TCIntensity="Tropical Depression";  TCimage="tdgoogle.png"; }
else if (TCwind < 88) { TCIntensity="Tropical Storm"; TCimage="tsgoogle.png";}
else if (TCwind < 118) { TCIntensity="Severe Tropical Storm"; TCimage="stsgoogle.png"; }
else if (TCwind < 150) { TCIntensity="Typhoon"; TCimage="tygoogle.png"; }
else if (TCwind < 185) { TCIntensity="Severe Typhoon"; TCimage="stygoogle.png"; }
else { TCIntensity="Super Typhoon"; TCimage="sutygoogle.png"; }
};

我将这个函数称为:

var TC1wind0 = 65;
var TC1image0 = "";
var TC1Intensity0 = "";
Intensity(TC1wind0, TC1Intensity0, TC1image0);

正确的结果应该在TC1Intensity0中存储“Tropical Storm”,在TC1image0中存储“tsgoogle.png”。然而,它没有给出正确的结果,如上述“浪费空间”方法。相反,该功能似乎不起作用。 TC1Intensity0和TC1image0都仍为“”。为什么会这样?

2 个答案:

答案 0 :(得分:2)

由于您传递的三个参数只是字符串,因此javascript将按值传递它们。这意味着在函数内部对TCwind进行更改不会在函数外部更改TCwind

最直接的方法是返回对象中的值:

var result = Intensity(65, '', '');
var TCwind = result.TCwind;
var TCimage = result.TCimage;
var TCIntensity = result.TCIntensity;

function Intensity(TCwind, TCIntensity, TCimage) {
    /* snip */
    return {
        TCwind: TCwind,
        TCIntensity: TCIntensity,
        TCimage: TCimage
    };
};

有关按值传递/按推荐传递的详细信息,请查看以下其他一些问题:

答案 1 :(得分:0)

更简单的是,您不将vars作为参数传递。 比该函数会在全局变量中写入。

function Intensity(TC1wind0){
[...]
}


var TC1wind0 = 65;
var TC1image0 = "";
var TC1Intensity0 = "";
Intensity(TC1wind0);