繁体   English   中英

无法返回数组的元素

[英]Having trouble returning an element of an array

所以我正在做一个免费的在线JavaScript课程。 我正在上课2.它专注于数组,对象和事件。 我在测验中做得很好,但不知道怎么做分配。 这是作业。

创建一个包含“January”到“December”的数组创建一个名为GetMonthName的函数,该函数将一个数字作为参数并返回该月份的名称。 例如:

得到月(3); //将返回Month

请记住,数组从0开始编号,但在这里,第1个月应该是1月。 所以你必须以某种方式解释这一点。

所以这是我的代码。 我在正确的轨道上吗? 任何帮助,将不胜感激。

//create array
var months = ["Month","January","February","March","April","May","June","July","August","September","October","November","December"];

//create function
function getMonthName(month) {
    for(i=0;i<=12;i++) {
        var getMonth=months[i];
        return getMonth;
    }
}

//call function
getMonthName(getMonth);

你不想在这里使用循环,因为你只返回一个月。 你可能想要这样的东西:

function getMonthName(month) {
   var getMonth=months[month];
   return getMonth;
}

或者更简单:

function getMonthName(month) {
   return months[month];
}

要处理0索引,您还可以从数组中删除“月”,只需修改索引:

function getMonthName(month) {
   return months[month-1];
}

您不需要使用for循环,只需返回值

return months[i - 1];

您不需要在数组中包含“Month”。 尝试做这样的事情

//create array
var months = ["January","February","March","April","May","June","July","August","September","October","November","December"];

//create function
function getMonthName(month) {
    return months[month-1]
}

这样,除了月份名称之外,您不必向数组添加任何内容

您将在没有任何条件的情况下从循环返回,因此您将始终返回数组中的第一个元素并停止循环。

如果它是使用循环的某种练习,那么你应该只在满足条件时返回,比如

function getMonthName(month) {
    for(i=0;i<=12;i++) {
        var getMonth=months[i];
        if( i == month ){
            return getMonth;
        }
    }
}

但是如果你真的想通过它的索引从数组中得到一个月,并将它从1开始,那么getMonthName(1) == "January"则:

var months = ["January","February","March","April","May","June","July","August","September","October","November","December"];
function getMonthName(month) {
  return months[ month + 1 ];
}

让我们看看你可以做些什么:

//create array
var months = ["Month","January","February","March","April","May","June","July","August","September","October","November","December"];

在函数首先我确保我的参数是整数然后我检查传递的数字是否在1到12之间,最后我根据传递的数字减去一个返回所选月份。

//create function
function getMonthName(month) {
    month = (parseInt(month) || 0) -1;
    return month>0 && month<13 ? months[month] : null;
}

//call function
getMonthName(1);

 var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; var getMonth = (function(index){ return this[index-1]; }).bind(months); var month = getMonth(1); document.getElementById('month').innerHTML = month; 
 <div id="month"></div> 

示例: https//jsfiddle.net/artamonovdev/s80rx6fg/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM