gpt4 book ai didi

javascript - 当我尝试对 "reuse"代码使用函数时,它给出了错误的结果

转载 作者:行者123 更新时间:2023-11-30 17:59:34 24 4
gpt4 key购买 nike

我的谷歌地图 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 中存储“热带 Storm ”,在 TC1image0 中存储“tsgoogle.png”。然而,它并没有像上面的“浪费空间”方法那样给出正确的结果。相反,该功能似乎不起作用。 TC1Intensity0 和 TC1image0 仍然给出“”。为什么会这样?

最佳答案

由于您传递的三个参数只是字符串,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
};
};

有关按值传递/按引用传递的更多信息,请查看其他一些问题:

关于javascript - 当我尝试对 "reuse"代码使用函数时,它给出了错误的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17364767/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com