gpt4 book ai didi

javascript - 将 for 循环内容移动到函数中

转载 作者:行者123 更新时间:2023-11-30 10:31:44 25 4
gpt4 key购买 nike

我有一个 for 循环来遍历数组并显示日期。我写了一些代码来将月份从数字转换为文本。代码如下所示:

for (var i=0; i < arrayLength; i++) {
//==== MONTH DATA
var month = data[1];

//==== DECLARE MONTH
if (month == '01') { var month = "Jan" }
if (month == '02') { var month = "Feb" }
if (month == '03') { var month = "Mar" }
if (month == '04') { var month = "Apr" }
if (month == '05') { var month = "May" }
if (month == '06') { var month = "June" }
if (month == '07') { var month = "July" }
if (month == '08') { var month = "Aug" }
if (month == '09') { var month = "Sept" }
if (month == '10') { var month = "Oct" }
if (month == '11') { var month = "Nov" }
if (month == '12') { var month = "Dec" }

alert(month);
}

现在我想在整个站点的各种 for 循环中使用月份转换器。所以我想做一些事情,比如把它放在一个我每次都可以触发的函数中。例如:

function declareMonth(){
//==== DECLARE MONTH
if (month == '01') { var month = "Jan" }
if (month == '02') { var month = "Feb" }
if (month == '03') { var month = "Mar" }
if (month == '04') { var month = "Apr" }
if (month == '05') { var month = "May" }
if (month == '06') { var month = "June" }
if (month == '07') { var month = "July" }
if (month == '08') { var month = "Aug" }
if (month == '09') { var month = "Sept" }
if (month == '10') { var month = "Oct" }
if (month == '11') { var month = "Nov" }
if (month == '12') { var month = "Dec" }
}

for (var i=0; i < arrayLength; i++) {
//==== MONTH DATA
var month = data[1];

declareMonth();

alert(month);
}

但这不起作用。谁能解释一下这是如何做到的?

最佳答案

您需要返回月份值。您还需要正确编写函数:

function getMonthName(n) {
var months = ["Jan", "Feb", ... ]; // omitted for brevity
return months[n - 1];
}

用法:

for (var i=0; i < arrayLength; i++) {
var month = data[1];
var name = getMonthName(month);
alert(name);
}

注意:如果提供的月份超出范围,结果将为 undefined

关于javascript - 将 for 循环内容移动到函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16507465/

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