0

I have a question about looping in JavaScript. Mostly I use jQuery but now I've decided to make an easy game in pure JavaScript.

if I loop through all my 'td' with this method it works, The cells[i] are td elements and I can attach events to them.

    for(i = 0; i < cells.length; i++){
        if(cells[i].nodeName == 'TD')
        {
            cells[i].onclick = function(){
                // call funciton on onclick
            };
        }
    }

But if I do like this, each element are just index numbers and the two at the end are length and item.

    for(var cell in cells){
        // cell is a number
    }

What's the difference and why doesn't the foreach-loop work like I want it to?

2 Answers 2

1

cell is a number because it is an index to the cells HTMLCollection. In the second loop you'd use the values like so:

for(var cell in cells){
    if(cells[cell].nodeName == 'TD')
    {
        cells[cell].onclick = function(){
            GameTurnExecute(player);
        };
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

cells is not an Array, but a HTMLCollection or NodeList.
0

You can also say:

for(var cell in cells){
    if(cells.hasOwnProperty(cell))
    {
        cells[cell].onclick = function(){
            GameTurnExecute(player);
        };
    }
}

not to see properties comming from prototype chain. (https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/hasOwnProperty)

In fact, almost everty time you use for in in javascript you want to use hasOwnProperty.

1 Comment

You are assuming that host object have prototype inheritance, which is not reasonable. They are not required to implement any inheritance pattern at all, and in at least one popular host environment, they don't.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.