Lógica de bucle for para crear dinámicamente un tiempo basado en un índice

So I've got 43 Radio buttons. When one of them is selected, it returns their index number. It's zero-based, so its 0-42. Each index corresponds to a particular time. 0 is 8:00am and 42 is 10:00pm, each index increase the time for 20 minutes. Essentially, I'm trying to generate the time I need without having to manually create if-statements for each index. Here's the broken code I have so far.

function decipherIndex(radx) {
    var actime = "";
    var hr = 8;
    var min = 0;
    var day = "am";
    for (i=0;i<radx;i++) {
        min = min + 20;
        if (min = 60) {
            hr = hr + 1;
            min = 0;
        }
        if (hr = 13) {
            hr = 0;
            day = "pm";
        }
    }
    actime = hr + ":" + min + day;
    alert(actime);
}

Hopefully someone can help me work through my logic here. radx is the index that's getting passed to the function.

preguntado el 03 de julio de 12 a las 23:07

1 Respuestas

if (min = 60) {
    hr = hr + 1;
    min = 0;
}
if (hr = 13) {
    hr = 0;
    day = "pm";
}

You're assigning with the =, asi que min y hr siempre será 0 y day siempre será "pm". Utilizar == or === comparar:

if (min == 60) {
    hr = hr + 1;
    min = 0;
}

if (hr == 13) {
    hr = 0;
    day = "pm";
}

However, a loop isn't necessary; all you need is a little bit of math.

function decipherIndex(i) {
    var t = 60 * 8 + i * 20;
    var min = t % 60;
    var hr = t / 60 | 0;

    return hr % 12 + ':' + (min < 10 ? '0' : '') + min + (hr >= 12 ? ' PM' : ' AM');
}

Respondido 03 Jul 12, 23:07

Información complementaria: === is a conversionless compare stackoverflow.com/questions/359494/… - laz

Mine is two characters shorter :P - mellamokb

Thanks, that was all I needed. - Vikram

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.