Question

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!

Was it helpful?

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

OTHER TIPS

Increment a counter, quit the loop when it hits 10

var i = 0;
for (var k in navigator) {
    i++;
    document.getElementById('divResult').innerHTML += i + ', ' + k + ': ' + navigator[k] + '<br />';
    if (i === 10) 
        break;
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top