vendredi 22 juillet 2016

javascript for-loop undefined index even with a closure

I've got this code :

function resetCases()
{
    for(var t = 0; t < tds.length; t++)
    {
        (function(t)
        {
            tds[t].style.border = "3px solid #CC0000";
         })(t);
    } 
}

function func() 
{
    var i = 0;
    var tds = new Array();
    for(var y = maxLC; y >= (-maxLC-1); y--)
    {
        // not the whole code is written, "div" exists...
        var tr = div.appendChild(document.createElement('tr'));
        for(var x = (-maxLC-1); x <= maxLC; x++)
        {
            i++;

            tds[i] = tr.appendChild(document.createElement('td'));
            tds[i].style.border = "3px solid black";

            subDiv[i] = tds[i].appendChild(document.createElement('div'));

            tds[i].onmouseout = function(){resetCases();};
        }
    }
}
func();

even if I remove the closure, the error

tds[t] is undefined

is still displayed in the console.

However, if I write

console.log(tds[t]);

instead of

tds[t].style.border = "3px solid #CC0000";

there is no more error...

What am I doing wrong ? thanks

Aucun commentaire:

Enregistrer un commentaire