简体   繁体   English

选择要循环的数组

[英]Choose which array to loop over

I am creating a javascript function to build the html for a calendar (in a <table> ) for the current month. 我正在创建一个JavaScript函数来为当月的日历(在<table> )构建html。 One of the parameters of the function is whether to write out the days of the week or use their initials. 该函数的参数之一是写出星期几还是使用其首字母缩写。 The full names and initials are both contained in arrays. 全名和缩写均包含在数组中。 The function will loop over one of the arrays to build the table cells that contain the days of the week. 该函数将遍历数组之一以构建包含一周中各天的表单元格。 What is the best way to pick which array to loop over? 选择要遍历哪个阵列的最佳方法是什么? Or should I be constructing this code in an entirely different way? 还是应该以完全不同的方式构造此代码?

Code to illustrate my question: 代码来说明我的问题:

buildCalendar(useFullNames){
    var fullNames = ['Sunday', 'Monday'], // etc.
        initials = ['S', 'M'],
        calString = '<tr>';

    if(useFullNames) {
        // use fullNames array in the loop 
    }     
    else {   
        // use initials array in loop
    }

    for(i=0; i<7; i++)
    {
        // Need to loop over the array picked above
        calString += '<td>' + relevantArray[i] + '</td>';
    }

    calString += '</tr>';
}
var relevantArray = useFullNames ? fullNames : initials;

What about something like this (pseudocode): 像这样的东西(伪代码)呢?

buildCalendar(dayOfWeekFormat){ //dayOfWeekFormat: "fullNames or "initials"
    var dayOfWeekFormat = { 
       fullNames: ['Sunday', ..., 'Saturday'],
       initials: ['S', ..., 'Sat']
    }
    var calString = '<tr>';

    for(i=0; i<7; i++)
    {
        // Need to loop over the array picked above
        calString += '<td>' + daysOfWeek[dayOfWeekFormat][i] + '</td>';
    }

    calString += '</tr>';
}

relevantArray is an awful variable name. relevantArray是一个糟糕的变量名。 It doesn't tell you anything about what's in it. 它没有告诉您任何有关其中的内容。

Well, like you have it set up, set the relevantArray variable 好吧,就像您已经设置好一样,设置relevantArray变量

buildCalendar(useFullNames){
    var fullNames = ['Sunday', 'Monday'], // etc.
        initials = ['S', 'M'],
        calString = '<tr>',
        relevantArray;

    if(useFullNames) {
        // use fullNames array in the loop 
        relevantArray = fullNames;
    }     
    else {   
        // use initials array in loop
        relevantArray = initials;
    }

    for(i=0; i<7; i++)
    {
        // Need to loop over the array picked above
        calString += '<td>' + relevantArray[i] + '</td>';
    }

    calString += '</tr>';
}

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

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