Search code examples
javascriptnavigatorfor-in-loop

Learning JavaScript - for-in statement with a max. result


I'm reading a book about JS, and I'm stuck with one of the excercises.

I wrote a for-in to display the browser properties.

    for (var i in navigator) {

    document.getElementById('divResult').innerHTML += i + ': ' + navigator[i] + '<br />';
};

Now is the question how can I display only the first 10 of the navigator properties?

Thnx for helping me out!


Solution

  • You're using an object, and unlike an array objects don't have a "length" property that lets you easily run a loop over them. There are lots of ways to do this, but the easiest way to understand when you're learning is to create a "counter" variable outside expression and check to see if its true:

    var counter = 0;
    
    for (var i in navigator) 
    {
        if ( counter <= 10 ) 
        {
           document.getElementById('divResult').innerHTML += i + ': ' + navigator[i] + '<br />';
           counter = counter + 1;
        }
    };
    

    There are other ways to cause the expression to stop, as mentioned above, but this (for me) was the easiest way to think about things when I started